【问题标题】:"AttributeError" while accessing instance variables访问实例变量时出现“AttributeError”
【发布时间】:2018-07-27 14:16:54
【问题描述】:

Python 在运行我的脚本时引发以下异常。有人可以解释为什么会发生这种情况以及如何解决吗?

Traceback (most recent call last):
  File "C:\Users\vinsunny\AppData\Local\Programs\Python\Python36\test.py", line 28, in <module>
    test.my_func()
  File "C:\Users\vinsunny\AppData\Local\Programs\Python\Python36\test.py", line 23, in my_func
    print('non secret no. from test_func: ', self.number2)
AttributeError: 'Test' object has no attribute 'number2'"
class Test():

    __class_secret_number = 100

    def __secret_func(self):
        self.number1 = 1
        self.__secret_number1 = 11
        print('You cannot see this unless accessing from the Class itself')

    def test_func(self):
        self.number2 = 2
        self.__secret_number2 = 22

    def my_func(self):
        self.__secret_func()
        print('Secret no. from class: ', self.__class_secret_number)

        print('non secret no. from secret func: ', self.number1)
        print('Secret no. from secret func: ', self.__secret_number1)

        # These two prints raise an exception.
        print('non secret no. from test_func: ', self.number2)
        print('Secret no. from test_func: ', self.__secret_number2)

test = Test()
test.my_func()

【问题讨论】:

  • 面临这个问题。在谷歌中挖掘,没有找到解决方案。
  • 你不要打电话给test_func。所以number2 永远不会被分配。

标签: python python-3.x instance-variables attributeerror


【解决方案1】:

test_func 永远不会被调用,所以 number2__secret_number2 不存在。

在尝试访问它们之前需要调用该函数,或者使用 init 方法对其进行初始化。

【讨论】:

  • 是的,兄弟.. 试过了。非常感谢。
【解决方案2】:

在执行有问题的打印语句时,您的 Test 实例上的 number2 属性尚未定义。

第一次设置number2 属性是在test_func() 方法中。即在调用test_func() 之前尝试访问number2 将导致您观察到的错误。

您应该在Test 类的初始化程序中为self.number2 分配一个默认值。您也可以在致电my_func() 之前致电test_func()。但是,无论哪种方式,初始化Test.__init__ 中的所有实例属性仍然是一种好习惯。

当您尝试访问my_func() 中的未定义属性__secret_number_2 时,解释器将出于同样的原因引发异常。

【讨论】:

  • 谢谢老兄。它正在工作。没想到。
  • 刚刚创建了 stackoverflow 帐户,所以我无法投票,因为我有
  • 已接受。是的,一旦我获得 15 声望,我肯定会回来的。
  • 谢谢!很高兴我能帮上忙!
  • 以 15+ 的声望回来了。为您的答案投票。再次感谢..
猜你喜欢
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
相关资源
最近更新 更多