【问题标题】:dict in __init__ cannot be accessed?__init__ 中的 dict 无法访问?
【发布时间】: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


【解决方案1】:

你忘了self

改变这个:

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

与:

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

self 是你的类方法中的instance。这并不是因为self 是一个特殊的关键字,而是因为self 通常是选择作为方法第一个参数的词。

如果您想了解更多关于self 的信息,here 有一个很好的答案。

最后通知您在尝试拨打电话时收到了AttributeError

t.test_dict

因为未定义 test_dict 属性。

【讨论】:

    【解决方案2】:

    您在__init__ 中出错。这个:

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

    应该是:

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

    【讨论】:

      【解决方案3】:

      将类/实例视为字典。每当您创建实例并调用其任何方法时,这些函数都会自动接收实例作为第一个参数(除非函数是静态或类方法)。

      因此,如果您希望将某个变量存储在实例中并稍后访问,请将所有变量放入第一个参数中(按照惯例,它称为 self)。

      类构造函数也不例外。这就是为什么所有答案都指出 test_dict 赋值中的构造函数发生了变化。

      想一想:

      self.test_dict = ...
      

      喜欢

      self.__dict__["test_dict"] = ...
      

      就像 Python 中的所有变量一样,如果没有先分配变量,您将无法访问它。您原来的班级就是这种情况:

      _init_ 创建了一个本地(方法)变量,而 test_function 正在尝试访问字典中的实例变量,这确实不存在。

      【讨论】:

        猜你喜欢
        • 2014-06-23
        • 2013-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-24
        • 1970-01-01
        • 2021-05-06
        • 2011-08-18
        相关资源
        最近更新 更多