classe python
# Standard way of writing a simple class
class Person1:
# Type hinting not required
def __init__(self, name: str, age: int, num_children=0):
self.name = name
self.age = age
self.num_children = num_children
def __repr__(self):
return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'
from dataclasses import dataclass
# A class using data classes. Dataclasses are simpler but can't support operations during initialization
@dataclass()
class Person2:
""" This class handles the values related to a person. """
name: str # Indicating types is required
age: int
num_children = 0 # Default values don't require an indication of a type
def __repr__(self):
return f'My name is {self.name}, I am {self.age} years old, and I have {self.num_children} children'
# Both classes (Person1 and Person2) achieve the same thing but require different code to do it
person1 = Person1('Joe', 28, 2)
print(person1)
# Result: My name is Joe, I am 28 years old, and I have 2 children
person2 = Person2('Emma', 19)
print(person2)
# Result: My name is Emma, I am 19 years old, and I have 0 children
YEP Python