Reputation: 2568
I want to call parent class method using super() in Python 2.
In Python 3, I'd code it like this:
class base:
@classmethod
def func(cls):
print("in base: " + cls.__name__)
class child(base):
@classmethod
def func(cls):
super().func()
print("in child: " + cls.__name__)
child.func()
with this output:
in base: child
in child: child
However, I have no idea, how do this in Python 2. Of course, I can use base.func()
, but I don't like to specify parent class name in addition and mainly I get unwanted result:
in base: base
in child: child
With cls
(cls is child
) as first argument in super()
function call, I get this error:
TypeError: must be type, not classobj
Any idea how do it using super()
or analogous function in which I don't have to specify name of parent class?
Upvotes: 2
Views: 3781
Reputation: 543
I was trying to do something similar where I was trying to basically "walk up" the inheritance chain until I found a certain base class and then do something there with the class name. The issue I was having was that ALL of these answers assume that you know the name of the class you are trying to get the super of. I tried the "super(cls, cls)" approach but got the "inifinite recursion" issue described above. Here is where I landed
@classmethod
def parent_name(cls):
if BaseDocument in cls.__bases__:
# This will return the name of the first parent that subclasses BaseDocument
return cls.__name__
else:
for klass in cls.__bases__:
try:
parent_name = klass.parent_name()
if parent_name is not None:
return parent_name
except AttributeError:
pass
return None
Upvotes: 0
Reputation: 113940
furthering the other answer you can do classmethods for it like
class base(object):
@classmethod
def func(cls):
print("in base: " + cls.__name__)
class child(base):
@classmethod
def func(cls):
super(cls, cls).func()
print("in child: " + cls.__name__)
child.func()
Upvotes: 4
Reputation: 300
You parent object needs to inherit from object in python 2. So:
class base(object):
def func(self):
print("in base")
class child(base):
def func(self):
super(child, self).func()
print("in child")
c = child()
c.func()
Upvotes: 1