Upon updating a value, the __init__ method still uses the old attribute value.
class Email:
def __init__(self, name):
self.name = na
In this example, self.email is being assigned in the __init__ method of the class, which is only called when an instance of Email is created. As such, when self.name is reassigned, self.email is not changed. To work around this, you can use a property decorator:
class Email:
def __init__(self, name):
self._name = name
self._email = f'{name}@hotmail.com'
def details(self):
return f'{self._name} | {self._email}'
@property
def name(self):
return self._name
@name.setter
def name(self, _new_name):
self._name = _new_name
self._email = f'{_new_name}@hotmail.com'
person = Email("James")
print(person.details())
person.name = "Michael"
print(person.details())
Output:
James | James@hotmail.com
Michael | Michael@hotmail.com