Can I pass python **kwargs to parent class from sub?

拜拜、爱过 提交于 2020-07-17 08:30:12

问题


I'd like to do something like this:

class A(object):
    def __init__(self, **kwargs):
       """ 
       return exception if certain arguments not set
       """

class B(A):
    def __init__(self, **kwargs):
       super(B, self).__init__(**kwargs)

Basically, each subclass will require certain arguments to be properly instantiated. They are the same params across the board. I only want to do the checking of these arguments once. If I can do this from the parent init() - all the better.

Is it possible to do this?


回答1:


Sure. This is not an uncommon pattern:

class A(object):
    def __init__(self, foo, bar=3):
        self.foo = foo
        self.bar = bar

class B(A):
    def __init__(self, quux=6, **kwargs):
        super(B, self).__init__(**kwargs)

        self.quux = quux

B(foo=1, quux=4)

This also insulates you a little from super shenanigans: now A's argspec can change without requiring any edits to B, and diamond inheritance is a little less likely to break.




回答2:


Absolutely. Parameter and keyword expansion will work naturally when fed into parameter and keyword arguments.



来源:https://stackoverflow.com/questions/14329552/can-i-pass-python-kwargs-to-parent-class-from-sub

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