【问题标题】:Why can't I access an class variable defined in __init__ from outside of the class?为什么我不能从类外部访问 __init__ 中定义的类变量?
【发布时间】:2018-05-19 06:47:03
【问题描述】:

我想知道类以及如何通过打印或使用 _str__ 函数从外部访问它们的值。我遇到了这个问题: Python function not accessing class variable

然后我在 Shell 中做了这个测试,但它没有按预期工作。我想知道为什么其他答案有效,但不是这个。

(编辑) 我的问题是通过如何实例化一个类而不是实例变量来回答的。

>>> class test:
    def __init__(self):
        self.testy=0
    def __str__(self):
        return self.testy


>>> a=test
>>> b=test
>>> print(a)
<class '__main__.test'>
>>> a
<class '__main__.test'>
>>> a.testy
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    a.testy
AttributeError: type object 'test' has no attribute 'testy'
>>> 

【问题讨论】:

标签: python python-2.7 class attributes


【解决方案1】:

您在创建对象时犯了一个错误,请找出以下区别:

class test:
def __init__(self):
    self.testy=0
def __str__(self):
    return self.testy

a = test()
b = test()
a.testy
       output: 0

你做了什么:

c = test
d = test
c.testy
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: type object 'test' has no attribute 'testy'

解释:

当您为班级创建objects 时,请使用object = class_name()

**https://docs.python.org/3/tutorial/classes.html#class-objects

【讨论】:

    【解决方案2】:

    你在 init 中定义你的变量,它只在类被实例化时被调用。如需更长的解释,我建议您参考您所链接问题的第一个答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多