无法访问实例属性
Can't access instance attributes
我尝试使用组合关系,但我无法访问化合物class A:
使用此代码,我试图将来自 class B.
的对象添加到 class A 的列表中
class B:
def __init__(self,X,Y,Z):
self.X
self.Y
self.Z
def Xreturner(self):
return self.X
def Yreturner(self):
return self.Y
def Zreturner(self):
return self.Z
class A:
def __init(self):
self.lst=[[1,2,3],[3,4,5],]
self.b=B()
def add(self): # trying to add b object to the list
self.lst.append(self.b)
#### TEST####
objA=A()
objA.add(6,7,8)
当我测试时出现这个错误:
Traceback (most recent call last):
File "home/testXYZ.py", line 28, in <module>
objA.add(6,7,8)
TypeError: add() takes exactly 1 argument (4 given)
请帮我解决这个问题。
B
的 __init__
方法中的语句 self.X
什么都不做。您需要输入 self.X = X
.
- 您正在向
add()
传递参数,但它不接受任何参数。也许您想添加参数(就像您为 X
的 __init__
添加参数一样。
- 也许您甚至想将参数传递给
A
的 __init__
(而不是传递给 A
)。然后你可以将它们传递给 B
. 的构造函数
首先,您的 class B
初始值设定项不正确:
class B:
def __init__(self, x, y, z): # <== should use snake_case for vars
self.x = x
self.y = y
self.z = z
接下来,您的 class A
添加应该创建一个新的 B 对象并添加到列表中:
def add(self, x, y, z):
new_b = B(x, y z)
self.lst.append(new_b)
我尝试使用组合关系,但我无法访问化合物class A: 使用此代码,我试图将来自 class B.
的对象添加到 class A 的列表中class B:
def __init__(self,X,Y,Z):
self.X
self.Y
self.Z
def Xreturner(self):
return self.X
def Yreturner(self):
return self.Y
def Zreturner(self):
return self.Z
class A:
def __init(self):
self.lst=[[1,2,3],[3,4,5],]
self.b=B()
def add(self): # trying to add b object to the list
self.lst.append(self.b)
#### TEST####
objA=A()
objA.add(6,7,8)
当我测试时出现这个错误:
Traceback (most recent call last):
File "home/testXYZ.py", line 28, in <module>
objA.add(6,7,8)
TypeError: add() takes exactly 1 argument (4 given)
请帮我解决这个问题。
B
的__init__
方法中的语句self.X
什么都不做。您需要输入self.X = X
.- 您正在向
add()
传递参数,但它不接受任何参数。也许您想添加参数(就像您为X
的__init__
添加参数一样。 - 也许您甚至想将参数传递给
A
的__init__
(而不是传递给A
)。然后你可以将它们传递给B
. 的构造函数
首先,您的 class B
初始值设定项不正确:
class B:
def __init__(self, x, y, z): # <== should use snake_case for vars
self.x = x
self.y = y
self.z = z
接下来,您的 class A
添加应该创建一个新的 B 对象并添加到列表中:
def add(self, x, y, z):
new_b = B(x, y z)
self.lst.append(new_b)