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 types. Sadly, I appear to have no idea how to make this work:
>>> class Super(object):
name = None
def __init__(self, *args, name=None, **kwargs):
self.name = name
super().__init__(self, *args, **kwargs)
>>> class Sub(Super, int):
pass
>>> Sub(5)
5
>>> Sub(5, name="Foo")
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
Sub(5, name="Foo")
TypeError: 'name' is an invalid keyword argument for this function
(I've also tried it without the super()
call, but the result was the same.)
Perhaps someone with better knowledge of multiple inheritance can point me in the right direction?
Update:
Here is the solution I ended up with, based on Alex's answer.
It's still a little hacky (by changining __new__
's signature partway through construction), but it will work as long as the superclass appears in the subclasses' MROs before the built-in type and defining __new__
this way allows me to make subclasses which work with different built-in types without adding a separate __new__
to each one.
>>> class Super(object):
name = None
def __new__(cls, *args, name=None, **kwargs):
inner = super().__new__(cls, *args, **kwargs)
inner.name = name
return inner
>>> class Sub(Super, int):
pass
>>> Sub(5)
5
>>> Sub(5, name="Foo")
5
>>> _.name
'Foo'