【问题标题】:Why doesn't Python instance variable work? [closed]为什么 Python 实例变量不起作用? [关闭]
【发布时间】:2020-06-27 10:31:31
【问题描述】:

为什么实例变量b不起作用:

class Clothing:
    a = 5

    def __init__(self):
        self.b = 0

shirt = Clothing
shirt.b

AttributeError: type object 'Clothing' 没有属性 'b'

为什么尝试访问 shirt.b 会引发 Attribute 错误?

【问题讨论】:

  • 实例化类。 shirt = Clothing()

标签: python python-3.x oop instance


【解决方案1】:

你需要括号,应该是shirt = Clothing()

【讨论】:

    【解决方案2】:

    这将起作用:

    class Clothing:
       a = 5
    
       def __init__(self):
          self.b = 0
    
    shirt = Clothing() # add the '()' here
    shirt.b
    print(shirt.b) #prints 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 2017-09-06
      • 1970-01-01
      • 2012-05-20
      • 2016-05-27
      • 2021-12-03
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多