我无法理解为什么即使在更改对象属性 self.name 和 self.author 之后,self.details 也会打印同一行。class Book(object): def __init__(self, name, author): self.name = name self.author = author self.details = self.name + ' written by ' + self.authorbk = Book("Harry Potter", "J K Rowling")print(bk.name)print(bk.author)print(bk.details) #Harry Potter written by J K Rowlingbk.name = 'Becoming'bk.marks= 'Michelle Obama'print(bk.name)print(bk.author)print(bk.details) #Harry Potter written by J K Rowling
2 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
因为details是从原始值创建的。连接发生后,它完全独立于其他值。如果您想要使用name/的当前值动态构造的字符串author,请使用 apropertydetails在访问时动态计算(根本不将其存储为属性):
class Book(object):
def __init__(self, name, author):
self.name = name
self.author = author
# Don't make a `details` attribute at all
@property
def details(self):
# This method is called whenever you refer to `somebook.details`
return self.name + ' written by ' + self.author
添加回答
举报
0/150
提交
取消