我想知道是否可以使用父构造函数来传递每个子类所需的参数。例如:
Class A():
def __init__(a,b):
...do some stuff...
Class B(A):
def __init__(c,d):
...do some stuff needing a and b...
Class C(A):
def __init__(e,f,g):
...do some stuff needing a and b...
基本上我的每个子类都需要一些参数,而另一些则是特定的。我不想在A的每个子类的定义中添加a,b。有什么方法可以在python中做到这一点吗?
我希望看到的是能够致电:
b=B(a=1,b=2,c=3,d=4)
,而不必在子类定义中包含a和b。
非常感谢!
答案 0 :(得分:3)
# Python 3, but the idea is the same in 2
class A:
def __init__(self, a, b):
# ...
class B(A):
def __init__(self, c, d, *args, **kwargs):
super().__init__(*args, **kwargs)
class C(A):
def __init__(self, e, f, g, *args, **kwargs):
super().__init__(*args, **kwargs)