Skip to content Skip to sidebar Skip to footer

Adding Optional Parameters To The Constructors Of Multiply-inheriting Subclasses Of Built-in Types?

My multiple-inheritance-fu is not strong. I am trying to create a superclass whose __init__ takes an optional named parameter and subclasses of it which also inherit from built-in

Solution 1:

You just cannot pass arbitrary parameters (whether positional or named ones) to an equally arbitrary superclass (i.e., "immediately previous type in the mro of whatever the current leaf type is") -- most types and classes just don't accept arbitrary parameters, for excellent reasons too -- quoting from the middle of the Zen of Python,

Errors should never pass silently.
Unless explicitly silenced.

and in most cases, calling (e.g.) int(name='booga')would of course be an error.

If you want you weirdly-named class Super to be able to "pass on" arbitrary parameters, you must also ensure that all classes ever used as bases after it can handle that -- so, for example, int can be called with one parameter (or exactly two: a string and a base), so, if it's absolutely crucial to you that class Subcan multiply inherit from the buck-passing Superand int, you have to field that, e.g.:

classInt(int):
    def __new__(cls, *a, **k):
        returnint.__new__(Int, a[0] if a else0)

Note that you must override __new__, not__init__ (it does no harm if you also override the latter, but it's irrelevant anyway): int is immutable so the value has to be set at __new__ time.

Now, things like

>>>classX(Super, Int): pass...>>>X(23, za='zo')
23
>>>

work. But note that X must subclass from Int (our __new__-sanitizing version of int), not from int itself, which, quite properly, has an unforgiving __new__!-)

Post a Comment for "Adding Optional Parameters To The Constructors Of Multiply-inheriting Subclasses Of Built-in Types?"