【问题标题】:Python class attributes within a list of instances are not recognized properly无法正确识别实例列表中的 Python 类属性
【发布时间】:2019-04-10 18:13:25
【问题描述】:

我第一次尝试在列表中使用类对象。但是由于某种原因,列表中所有类对象的属性都被分配了与列表中最后一个对象相同的值。这是我的代码:

# First I define the class
class Batsman:
   def __init__(self, innings, avg, sr):
       Batsman.innings = innings
       Batsman.avg = avg
       Batsman.sr = sr

# Then I create the list of class objects:
batsman = [
        Batsman(100,45,65),
        Batsman(50,40,60)
]

# Then I print the below:

print(batsman[0].innings)

输出应该是 100,但实际上是 50。为什么是这样? 如果我使用 5 个实例,则所有 5 个实例的属性都会重置为最后一个对象包含的任何内容。这是为什么呢?

【问题讨论】:

标签: python class instance class-attributes


【解决方案1】:

当使用Batsman类的名称时,你指的是类而不是实例,你需要使用self:

class Batsman:
   def __init__(self, innings, avg, sr):
       self.innings = innings
       self.avg = avg
       self.sr = sr

# Then I create the list of class objects:
batsman = [
        Batsman(100,45,65),
        Batsman(50,40,60)
]

# Then I print the below:

print(batsman[0].innings)

您可以在此other question 中查看有关self 的一些额外解释和信息

【讨论】:

  • 谢谢!我的错。
猜你喜欢
  • 2013-07-06
  • 1970-01-01
  • 2012-08-11
  • 2023-03-10
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
相关资源
最近更新 更多