[英]Pass required positional argument to super class without adding it in subclass' constructor
I have such a class: 我有这样的课:
class C1:
def __init__(self, arg1, kwarg1=1, kwarg2=2):
...
Now I want to create a C2
that just changes default values of kwarg1
and kwarg2
in C1
. 现在,我想创建一个C2
,只更改C1
中kwarg1
和kwarg2
默认值。 It's some sort of functools.partial
but for classes. 这是某种functools.partial
但用于类。
I can do it it this way: 我可以这样做:
class C2(C1):
def __init__(self, arg1, kwarg1=3, kwarg2=4):
super().__init(arg1, kwarg1=kwarg1, kwarg2=kwarg2)
But I don't like that I need to pass arg1
to C2
constructor and then pass it as it is to C1
with super().__init(arg1, ...)
. 但是我不喜欢这样,我需要将arg1
传递给C2
构造函数,然后使用super().__init(arg1, ...)
将它原样传递给C1
。
I'd like to do something like this: 我想做这样的事情:
class C2(C1):
def __init__(self, kwarg1=3, kwarg2=4, *args, **kwargs):
super().__init(kwarg1=kwarg1, kwarg2=kwarg2, *args, **kwargs)
but this doesn't work: 但这不起作用:
TypeError: __init__() missing 1 required positional argument: 'arg1'
Is there any way I can pass arg1
to C1
from C2
without mentioning it in C2
's constructor 有什么办法可以将arg1
从C2
传递到C1
,而无需在C2
的构造函数中提及
You can do it on an even more convoluted way, but at least you won't be passing the dreaded arg1
: 您可以以更复杂的方式进行操作,但是至少您不会传递可怕的arg1
:
class C2(C1):
def __init__(self, *args, **kwargs):
kwargs["kwarg1"] = kwargs.get("kwarg1", 3)
kwargs["kwarg2"] = kwargs.get("kwarg2", 4)
super().__init__(*args, **kwargs)
But you'll still need to keep your positional arguments when initializing C2
. 但是在初始化C2
时,仍然需要保留位置参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.