【问题标题】:What can't I print out the value of a instance attribute derived from other instance attributes?什么不能打印出从其他实例属性派生的实例属性的值?
【发布时间】:2021-09-09 09:48:01
【问题描述】:

我对 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 为空时,您将info_count 设置为info 的长度。那是零。
  • __init__ 函数设置行内info 的长度,您将在其中创建类的新实例。然后你向info 添加一些东西,但info_count 不会更新。这是 Python 类的基础知识,我认为您应该在发布此问题之前了解更多相关信息。
  • 谢谢。现在我明白我错在哪里了。

标签: python python-3.x class instance-variables derived-attribute


【解决方案1】:

您首先将 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

【讨论】:

  • 啊,现在我明白我哪里出错了。非常感谢!
猜你喜欢
  • 2020-03-28
  • 2016-03-03
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
相关资源
最近更新 更多