How to override constructor of Python class with many arguments?

守給你的承諾、 提交于 2019-12-18 10:34:19

问题


Say, I have a class Foo, extending class Bar. And I want to slightly override Foo's consructor. And I don't want even know what signarure of Bar's constructors is. Is there a way to do this?

If you didn't understand, I mean the following:

class Bar:
   def __init__ (self, arg1=None, arg2=None, ... argN=None):
      ....


class Foo (Bar):
    #Here i just want add additional parameter to constructor, but don't want to know anything about Bar's other parameters (arg1, arg2..., argN)
    def __init__ (self, my_new_arg=None, ??? )
       self.new_arg = my_new_arg
       Bar.__init__(self, ??? )

Is there a way to put something short and elegant instead of ??? in this code? (Maybe some variations of args/kwargs)


回答1:


class Parent(object):
    def __init__(self, a, b):
        print 'a', a
        print 'b', b

class Child(Parent):
    def __init__(self, c, d, *args, **kwargs):
        print 'c', c
        print 'd', d
        super(Child, self).__init__(*args, **kwargs)

test = Child(1,2,3,4)

Output:

c 1
d 2
a 3
b 4



回答2:


The *args, **kwds solution presented by @Acorn is a good start (though I take issue with the *args part of the answer). This approach is presented with a number of refinements in the article, Python's Super Considered Super.

The *args part is ill-advised because it is doesn't allow you to insert new classes in the hierarchy and it precludes subclasses from using multiple inheritance with other classes that may have incompatible positional arguments. The **kwds approach works much better because it doesn't enforce a particular ordering of the call chain.

Also note, you can use named arguments to separate and remove the current method's named arguments from the rest of the keyword arguments before they get passed up the chain:

class Bar(object):
   def __init__(self, arg1=None, arg2=None, argN=None):
       print arg1, arg2, argN

class Foo(Bar):
    def __init__(self, my_new_arg=None, **kwds):
       super(Foo, self).__init__(**kwds)
       self.new_arg = my_new_arg
       print my_new_arg

f = Foo(my_new_arg='x', arg2='y')

Having each method strip-off the arguments it needs is important because a parent method such as object.__init__ expects no arguments at all.

One final note, if you're going to use super, be sure that your top most class is new-style (i.e. it inherits from object or some other builtin type).



来源:https://stackoverflow.com/questions/8333354/how-to-override-constructor-of-python-class-with-many-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!