python - 使用 super() 从多个类函数继承变量
问题描述
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'
返回错误。我怎样才能继承初始化变量呢?
解决方案
您首先需要调用super
构造函数,因为您没有var
在base
类构造函数中定义。
您的代码的工作版本(尽管您可能应该在 base 中添加 var __init__
)
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
推荐阅读
- c# - 按 id 从数据库中加载行
- selenium-webdriver - 在 Jmeter 中停止 Selenium WebDrvier 测试
- android - android content provider方法是否需要同步?
- python - 如何使用 SQLAlchemy ORM 插入子查询(将数据从一个表移动到另一个表)
- jsf - 关闭所有面板并使用 p:ajax 更新动态 p:accordionPanel
- python - 类型错误:参数 1 具有意外类型“QPushButton”
- linux - 查找和复制命令在 bash 中不起作用
- python - Python:dropbox API 中的sharing_get_shared_link_file() 示例
- google-sheets - 如何使用 v 查找以降序显示另一个工作表中的值
- c# - DbCommand.Cancel 方法是否使用超时?