即使更改对象属性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
答案 0 :(得分:4)
因为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
答案 1 :(得分:3)
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