将子方法调用到父 class 并收到与无属性相关的错误
Calling child method to parent class and getting error related to no attribute
以下是示例代码。我正在尝试在大量代码中实现类似的功能。
我对此进行了足够的研究,但找不到与我的问题相关的任何具体解释。
class A:
def __init__(self,a,b):
self.a = a
self.b = b
self.e = self.gete()
def typing(self):
return self.d
def gete(self):
return self.d +1
class B(A):
def __init__(self,a,b,c):
super().__init__(a,b)
self.c = c
self.d = self.getd()
def getd(self):
return self.c+1
kk = B(1,2,3)
print(kk.typing())
print(kk.e)
我的预期结果是 5。但相反,它引发了错误。
"AttributeError: 'B' object has no attribute'"
但实际上它有一行
"self.d = self.getd()"
.
在您的 B.__init__()
中,您在分配 self.d
之前调用 super().__init__()
。因此,在调用时A.__init__()
,对象上没有d
属性,所以A.gete()
失败。
要解决此问题,您可以在 B.__init__()
中设置 self.d
后调用 super().__init__()
。
以下是示例代码。我正在尝试在大量代码中实现类似的功能。
我对此进行了足够的研究,但找不到与我的问题相关的任何具体解释。
class A:
def __init__(self,a,b):
self.a = a
self.b = b
self.e = self.gete()
def typing(self):
return self.d
def gete(self):
return self.d +1
class B(A):
def __init__(self,a,b,c):
super().__init__(a,b)
self.c = c
self.d = self.getd()
def getd(self):
return self.c+1
kk = B(1,2,3)
print(kk.typing())
print(kk.e)
我的预期结果是 5。但相反,它引发了错误。
"AttributeError: 'B' object has no attribute'"
但实际上它有一行
"self.d = self.getd()"
.
在您的 B.__init__()
中,您在分配 self.d
之前调用 super().__init__()
。因此,在调用时A.__init__()
,对象上没有d
属性,所以A.gete()
失败。
要解决此问题,您可以在 B.__init__()
中设置 self.d
后调用 super().__init__()
。