避免在子类中指定的所有参数 [英] Avoid specifying all arguments in a subclass
问题描述
我有一个类:
class A(object):
def __init__(self,a,b,c,d,e,f,g,...........,x,y,z)
#do some init stuff
和我有,需要一个额外的ARG一个子类(最后一个是W
)
And I have a subclass which needs one extra arg (the last W
)
class B(A):
def __init__(self.a,b,c,d,e,f,g,...........,x,y,z,W)
A.__init__(self,a,b,c,d,e,f,g,...........,x,y,z)
self.__W=W
这似乎愚蠢写这一切锅炉板code,如通过所有的ARGS从 B
的构造函数到里面调用 A
的构造函数,从此以后每次更改 A
的构造函数必须适用于其他两个地方在乙
的code。
It seems dumb to write all this boiler-plate code, e.g passing all the args from B
's Ctor to the inside call to A
's ctor, since then every change to A
's ctor must be applied to two other places in B
's code.
我猜测的Python有一些成语来处理这样的案件,我不知道。你能指出我朝着正确的方向吗?
I am guessing python has some idiom to handle such cases which I am unaware of. Can you point me in the right direction?
我最好的预感,就是有一种拷贝构造函数对于A,然后更改B的code到
My best hunch, is to have a sort of Copy-Ctor for A and then change B's code into
class B(A):
def __init__(self,instanceOfA,W):
A.__copy_ctor__(self,instanceOfA)
self.__W=W
给出的父类的实例时这会适合我的需要,因为我总是创建的子类,虽然我不知道它是否是可能的...
This would suit my needs since I always create the subclass when given an instance of the father class, Though I am not sure whether it's possible...
推荐答案
考虑到参数既可以按名称或位置进行传递,我想code:
Considering that arguments could be passed either by name or by position, I'd code:
class B(A):
def __init__(self, *a, **k):
if 'W' in k:
w = k.pop('W')
else:
w = a.pop()
A.__init__(self, *a, **k)
self._W = w
这篇关于避免在子类中指定的所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!