0

Why the "fullname" not update ?

Here is my code: class Person(): def __init__(self, firstname, lastname): self.first = firstname self.last = lastname self.fullname = self.first + ' '+ self.last def email(self): return '{}.{}@email.com'.format(self.first, self.last) person = Person('joe', 'lee') # 1. Here is the define of name original person.last = 'lin' # 2. I change the the last name from "lee" to "lin". print(person.first) # 3. Now I print: first name not change, output: "joe" print(person.last) # 4. Now I print: last name has changed: output: "lin" print(person.fullname) # Q: Why ??!! Why the fullname still "joe lee" ??? It was supposed to be "joe lin"... It's strange !!!

11th Apr 2019, 3:12 PM
Joe Lishuai Lin
Joe Lishuai Lin - avatar
2 odpowiedzi
+ 1
You can (and should) make fullname a read-only property that will always return the current values of first name and last name: class Person(): def __init__(self, firstname, lastname): self.first = firstname self.last = lastname @property def fullname(self): return self.first + ' ' + self.last person = Person('Joe', 'Lee') person.last = 'Lin' print(person.fullname) # Joe Lin (same with e-mail)
11th Apr 2019, 4:44 PM
Anna
Anna - avatar