简体   繁体   English

我可以将python ** kwargs从sub传递给父类吗?

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

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. 如果我可以从父init ()做到这一点 - 那就更好了。

Is it possible to do this? 是否有可能做到这一点?

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. 这也使你与super恶作剧有点隔离:现在A的argspec可以改变而不需要对B进行任何编辑,并且钻石继承不太可能破坏。

Absolutely. 绝对。 Parameter and keyword expansion will work naturally when fed into parameter and keyword arguments. 当输入参数和关键字参数时,参数和关键字扩展将自然地起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM