Skip to main content
 首页 » 编程设计

python之无法访问 __init__ 中的字典

2025年05月04日14arxive

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?

请您参考如下方法:

您忘记了self。

改变这个:

def __init__(self): 
    test_dict = {'1': 'one', '2': 'two'} 

与:

def __init__(self): 
    self.test_dict = {'1': 'one', '2': 'two'} 

self 是您类中方法内的实例。这不是因为 self 是一个特殊的关键字,而是因为 self 通常是被选为方法第一个参数的词。

如果你想更多地了解self,有一个很好的答案here .

最后请注意,当您尝试调用时出现了 AttributeError

t.test_dict 

因为未定义 test_dict 属性。