Dataclasses were added in Python 3.7 and they add a decorator for automatically adding special methods such as __init__() and __repr__() to user defined classes.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int = 0
def introduce(self) -> str:
return f"Hi, my name is {self.name} and my age is {self.age}."It works as expected:
person1 = Person("Jill", 23) # constructor is overloaded
print(person1.introduce()) # function works
print(person1) # __repr__() is correctly overloaded -- Person(name='Jill', age=23)
person2 = Person(name="Joe", age=46) # can pass hashes like so
print(person1 == person2) # __eq__() is correctly overloaded -- False