简体   繁体   中英

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 . It's some sort of functools.partial but for classes.

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, ...) .

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

You can do it on an even more convoluted way, but at least you won't be passing the dreaded 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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