class base():
def __init__(self):
self.var = 10
def add(self, num):
res = self.var+num
return res
class inherit(base):
def __init__(self, num=10):
x = super().add(num)
a = inherit()
print(a)
你好,我正在学习继承和super()。运行此命令时,返回错误AttributeError: 'inherit' object has no attribute 'var'
。我怎么能继承init变量?
您首先需要调用super
构造函数,因为您没有在base
类构造函数中定义var
。
您的代码的工作版本(尽管您可能应该在基础__init__
中添加var)
class Base:
def __init__(self):
self.var = 10
def add(self, num):
res = self.var + num
return res
class Inherit(Base):
def __init__(self, num=10):
super().__init__()
x = super().add(num)
a = Inherit()
print(a)
一个可能的解决方案
class Base:
def __init__(self, var=10):
self.var = var
def add(self, num):
res = self.var + num
return res
class Inherit(Base):
pass
a = Inherit()
a.add(0) # replace 0 with any integer