简体   繁体   English

将所需的位置参数传递给超类,而无需将其添加到子类的构造函数中

[英]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 ,只更改C1kwarg1kwarg2默认值。 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 有什么办法可以将arg1C2传递到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.

相关问题 在python构造函数中缺少1个必需的位置参数 - Missing 1 required positional argument in python Constructor 从子类调用超类构造函数的原因? - Reason for calling super class constructor from subclass? 类型错误:在调用 super.__init__() 时缺少 1 个必需的位置参数 - TypeError: missing 1 required positional argument in call to super.__init__() 使用python定义超级简单函数,但“缺少1个必需的位置参数” - Defining super easy function with python but “missing 1 required positional argument” __init__() 缺少 1 个必需的位置参数:扩展 class 时出现“请求”父构造函数错误 - __init__() missing 1 required positional argument: 'request' parent constructor error while extending class TypeError:__init __()在子类中缺少1个必需的位置参数 - TypeError: __init__() missing 1 required positional argument in subclass 类变量-缺少一个必需的位置参数 - Class variables - missing one required positional argument 为什么我不能在类中的方法之间传递这个变量? “缺少 1 个必需的位置参数” - Why can't I pass this variable between methods in a class? "missing 1 required positional argument" 必需的位置参数:'self' - Required positional argument: 'self' 缺少必需的位置参数: - Missing required positional argument:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM