【发布时间】: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'
>>>
【问题讨论】:
-
a = test()print(a.testy) -
你永远不会实例化你的类。
-
所以 a 充当类的指针,而不是实际类的成员,对吧?
标签: python python-2.7 class attributes