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

后端 未结 4 1835
闹比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 10:19

    As @Ajax1234 saying, the init function is calling when you create a new instance. Think it like a constructor if you are familiar with an object oriented language.

    So, if you just change the person.name, you can change the name field but not the email variable which assigned with older value of name.

    You have a few options about that case:

    • You can create a new Email object with name of Michael.

    • You can re-assign the e-mail directly, like you do in init function.

    • You can create a "setter" method for name like setName(name) and you can update the email in this function. So, when you call the setter, it automatically updates the email.

提交回复
热议问题