为什么通过合并其他属性创建的实例属性不会改变,即使原始属性被覆盖

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


繁花如伊
浏览 136回答 2
2回答

Smart猫小萌

因为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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python