【发布时间】:2010-11-21 06:00:35
【问题描述】:
我有一个 Python 类
class pytest:
i = 34
def func(self):
return "hello world"
当我访问pytest.i 时,我得到 34。我也可以通过其他方式做到这一点:
a = pytest()
a.i
这也给出了 34。
如果我尝试访问(不存在的)pytest.j,我会得到
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
pytest.j
AttributeError: class pytest has no attribute 'j'
当我尝试a.j 时,错误是
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
a.j
AttributeError: pytest instance has no attribute 'j'
所以我的问题是:这两种情况到底发生了什么,有什么区别?
【问题讨论】: