【发布时间】: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