【发布时间】:2019-06-03 01:51:40
【问题描述】:
我是 OOP 新手,正在尝试使用两个类。我正在尝试提供一个直到 Class1 运行到 Class2 时才创建的属性,但是当我运行 Class1 时出现 AttributeError。
class Class1():
#some code....
def function1():
x=5
number=2
test=class2(x)
answer=Class2.function2(Class2,number)
print(answer)
class Class2():
def __init__(self, y):
self.y=y
def function2(self, z):
calculated_answer=self.y+z
return calculated_answer
#several more functions that also use y
我试图避免在Class2 的每个新函数中重复将y 定义为x,所以我想我可以将Class2 与x 一起运行,然后将function2 与数字一起使用打印7。相反,我得到:AttributeError: type object 'Class2' has no attribute 'y'。
本来以为是误会__init__,所以跑了这段代码确认一下:
class Class2():
def __init__(self, y):
self.y=y
def function2(self, z):
calculated_answer=self.y+z
return calculated_answer
x=5
test=class2(x)
但是当我在 shell 中输入 test.function2(2) 并按预期返回 7 时,这可以正常工作。
我想我一定是误解了如何使用Class2,但我无法弄清楚我做错了什么。
在Class2 的每个函数中不只定义x 的情况下,如何消除此错误?
【问题讨论】: