无法访问__init__中的字典?

Sea*_*ene 1 python dictionary init

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
Run Code Online (Sandbox Code Playgroud)

错误:

AttributeError: test instance has no attribute 'test_dict'
Run Code Online (Sandbox Code Playgroud)

此外,如果我执行代码:t.test_function()而不是print t.test_dict,也发生错误:

AttributeError: test instance has no attribute 'test_dict'
Run Code Online (Sandbox Code Playgroud)

为什么?我已经在函数中定义了test_dict __init__,所以它应该初始化为每个实例,但为什么python告诉我它找不到dict?

Rik*_*ggi 6

你忘了self.

改变这个:

def __init__(self):
    test_dict = {'1': 'one', '2': 'two'}
Run Code Online (Sandbox Code Playgroud)

有:

def __init__(self):
    self.test_dict = {'1': 'one', '2': 'two'}
Run Code Online (Sandbox Code Playgroud)

self是你班级中方法的实例.这不是因为它self是一个特殊的关键字,而是因为self通常选择这个词作为方法的第一个参数.

如果您想了解更多有关self,有一个很好的答案在这里.

最后通知你有一个AttributeError当你试图打电话

t.test_dict
Run Code Online (Sandbox Code Playgroud)

因为test_dict没有定义属性.