Today I`m going to quickly show you how you can save a bunch of time and code when writing classes.
Typically when writing a class we do something like this.
class Interface:
def __init__(self, name: str, speed: int, mtu: int) -> None:
self.name = name
self.speed = speed
self.mtu = mtu
def __str__(self):
return "__str__"
def __repr__(self):
return "__repr__"
def __eq__(self, other):
return True
# Create instance
>>> rtr_interface = Interface(name="gi0/1", speed="1000", mtu="1500")
# Show instance representation (`__repr__`)
>>> rtr_interface
'__repr'
# Show string representation of instance (`__str__`)
>>> print(rtr_interface)
'__str__'
# Perform equal based comparision
>>> rtr_interface == rtr_interface
True
The main point here is that we need some code for the instance creation (__init__
) and assigning the variables at instantiation, along with having to assign the other special methods such as __repr__
, __str__
and __eq__
.
Let me introduce you to Data Classes, in short,
... data classes reduce the amount of boiler plate code required when writing classes. By default a data class will generate the special methods init, repr, str and eq for you.
For example:
from dataclasses import dataclass
@dataclass
class Interface:
name: str
speed: int
mtu: int
>>> rtr_interface = Interface(name="gi0/1", speed="1000", mtu="1500")
>>> rtr_interface
Interface(name='gi0/1', speed='1000', mtu='1500')
>>> print(rtr_interface)
Interface(name='gi0/1', speed='1000', mtu='1500')
>>> rtr_interface == rtr_interface
True
Cool, right! Data Classes can do a ton of other stuff as well which is covered below in more detail: