Goal
I learn composition OOP pattern with Python and I want to define a relation HAS-A from one class to another
Test
Here the Person class has a illness property with the help of the Medical class :
@dataclass
class Medical:
DISEASES: ClassVar[list] = [
'flue',
'polio',
'covid']
_disease: str = None
@property
def disease(self):
return self._disease
@disease.setter
def disease(self, value):
if value in type(self).DISEASES:
self._disease = value
class Person(object):
def __init__(self, name: str, age: int, illness=Medical()):
self.name = name
self.age = age
self._illness = illness
@property
def illness(self):
return self._illness.disease
def set_illness(self, value):
self._illness.disease = value
Issue
When instantiating the first Person object, it's going fine. But the one after, the Medical class is not responding as intended and I can find why :
joe = Person("joe", 12)
vars(joe)
>>> {'name': 'joe', 'age': 12, '_illness': Medical(_disease=None)}
joe.set_illness('flue')
vars(joe)
>>> {'name': 'joe', 'age': 12, '_illness': Medical(_disease='flue')}
bill = Person("bill", 13)
vars(bill)
>>> {'name': 'bill', 'age': 13, '_illness': Medical(_disease='flue')} # should be `'_illness': Medical(_disease=None)`