Calling superclass constructors in python with different arguments(在 python 中使用不同的参数调用超类构造函数)
问题描述
class A():
def __init__( self, x, y):
self.x = x
self.y = y
class B():
def __init__( self, z=0):
self.z = z
class AB(A,B):
def __init__( self, x, y, z=0):
?
如何让 AB 的构造函数使用正确的参数调用 A 和 B 的构造函数?
How can I make the constructor of AB call the constructors for A and B with the proper arguments?
我试过了
class AB(A,B):
def __init__( self, x, y, z=0):
A.__init__(x,y)
B.__init__(z)
但这给了我一个错误.
推荐答案
你没有通过self
.
class AB(A, B):
def __init__(self, x, y, z=0):
A.__init__(self, x, y)
B.__init__(self, z)
请注意,如果此继承层次结构变得更加复杂,您将遇到构造函数不执行或重新执行的问题.查看 super
(和problems 和 super
),别忘了继承自 object
如果你在 2.x 上并且你的类没有从其他任何东西继承.
Note that if this inheritance hierarchy gets more complicated, you'll run into problems with constructors not executing or getting reexecuted. Look into super
(and the problems with super
), and don't forget to inherit from object
if you're on 2.x and your class doesn't inherit from anything else.
这篇关于在 python 中使用不同的参数调用超类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 python 中使用不同的参数调用超类构造函数


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01