为什么合并其他属性创建的实例属性不会更改,即使原始属性被覆盖也是如此

问题描述 投票:0回答:2

我无法理解为什么即使在更改对象属性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
python
2个回答
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

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.nameself.author制作一个setter,自动更新self.details

© www.soinside.com 2019 - 2024. All rights reserved.