什么不能打印出从其他实例属性派生的实例属性的值?

问题描述

我对 Python 还很陌生,如果有人能帮助我解决我面临的这个问题,我将不胜感激。

这是我的代码

class Player:
def __init__(self,name):
    self.name = name
    self.info = {}
    self.info_count = len(self.info)



tom = Player("tom")
tom.info["Name"] = "tom"
tom.info["Height"] = "167cm"
print(tom.info)
print(tom.info_count)

输出

{'Name': 'tom','Height': '167cm'}
0

我正在尝试获取一个实例属性,该属性自动保存我拥有的信息数量。当 info 变量中有 2 个信息时,为什么输出仍然为 0?谢谢!

解决方法

您首先将 info_count 设置为 0,但随后它不再被修改,您分配一个而不是指向 info dict 某些属性的链接 .

init            -> info={}                                info_count=len(info)=0
info["name"]    -> info={'Name':'tom'}                    info_count = 0 
info["Height"]  -> info={'Name':'tom','Height':'167cm'}  info_count = 0

您需要的是一个 property

class Player:
    def __init__(self,name):
        self.name = name
        self.info = {}

    @property
    def info_count(self):
        return len(self.info)


tom = Player("tom")
tom.info["Name"] = "tom"
tom.info["Height"] = "167cm"
print(tom.info)       # {'Name': 'tom','Height': '167cm'}
print(tom.info_count) # 2