我无法理解为什么即使在更改对象属性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.author
bk = Book("Harry Potter", "J K Rowling")
print(bk.name)
print(bk.author)
print(bk.details) #Harry Potter written by J K Rowling
bk.name = 'Becoming'
bk.marks= 'Michelle Obama'
print(bk.name)
print(bk.author)
print(bk.details) #Harry Potter written by J K Rowling
因为details
是从原始值创建的。连接发生后,它完全独立于其他值。如果你想要一个动态构造的字符串,使用name
/ author
的当前值,use a property
在访问时动态计算details
(根本不存储它作为属性):
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
self.details
在做self.details = self.name + ' written by ' + self.author
时创建并设置一次,但它没有与之相关联。 +
操作只是串联串联。
确切地说,在你的第一个例子中,Python读取self.details = self.name + ' written by ' + self.author
所以它做self.details = "Harry Potter" + ' written by ' + "J K Rowling"
所以self.details = "Harry Potter written by J K Rowling"
它只是一个以字符串作为其值的属性。在您明确更改之前,此字符串将保持不变。
如果你想要这种行为,你可以查看getter和setter,并为self.name
和self.author
制作一个setter,自动更新self.details