【发布时间】:2012-02-24 12:18:32
【问题描述】:
class test:
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
def test_function(self):
print self.test_dict
if __name__ == '__main__':
t = test()
print t.test_dict
错误:
AttributeError: test instance has no attribute 'test_dict'
另外,如果我执行代码:t.test_function() 而不是print t.test_dict,也会发生错误:
AttributeError: test instance has no attribute 'test_dict'
为什么?我在函数__init__中定义了test_dict,所以它应该被初始化为每个实例,但是为什么python告诉我它找不到dict?
【问题讨论】:
-
如果您养成良好的命名习惯,例如 PEP8 中描述的那些,从长远来看,您会很高兴。类名 'test' 与语句
t = test()中的函数无法区分,但如果您将类名大写,那么t = Test()非常明显地构造了类 Test 的新实例。
标签: python dictionary init