Method attribute is not updating itself even though I'm clearly assigning a different value to it

后端 未结 4 1782
闹比i
闹比i 2021-01-07 09:38

Upon updating a value, the __init__ method still uses the old attribute value.

class Email:
    def __init__(self, name):
        self.name = na         


        
4条回答
  •  温柔的废话
    2021-01-07 09:59

    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
    

提交回复
热议问题