Question

Consider the following code:

class Base(object):

    @classmethod
    def do(cls, a):
        print cls, a

class Derived(Base):

    @classmethod
    def do(cls, a):
        print 'In derived!'
        # Base.do(cls, a) -- can't pass `cls`
        Base.do(a)

if __name__ == '__main__':
    d = Derived()
    d.do('hello')

> $ python play.py  
> In derived! 
> <class '__main__.Base'> msg

From Derived.do, how do I call Base.do?

I would normally use super or even the base class name directly if this is a normal object method, but apparently I can't find a way to call the classmethod in the base class.

In the above example, Base.do(a) prints Base class instead of Derived class.

Was it helpful?

Solution

If you're using a new-style class (i.e. derives from object in Python 2, or always in Python 3), you can do it with super() like this:

super(Derived, cls).do(a)

This is how you would invoke the code in the base class's version of the method (i.e. print cls, a), from the derived class, with cls being set to the derived class.

OTHER TIPS

this has been a while, but I think I may have found an answer. When you decorate a method to become a classmethod the original unbound method is stored in a property named 'im_func':

class Base(object):
    @classmethod
    def do(cls, a):
        print cls, a

class Derived(Base):

    @classmethod
    def do(cls, a):
        print 'In derived!'
        # Base.do(cls, a) -- can't pass `cls`
        Base.do.im_func(cls, a)

if __name__ == '__main__':
    d = Derived()
    d.do('hello')

This works for me:

Base.do('hi')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top