-->

Calling parent's __call__ method within class

2019-02-17 01:09发布

问题:

I'd like to call a parent's call method from inherited class

Code looks like this

#!/usr/bin/env python

class Parent(object):

    def __call__(self, name):
        print "hello world, ", name


class Person(Parent):

    def __call__(self, someinfo):                                                                                                                                                            
        super(Parent, self).__call__(someinfo)

p = Person()
p("info")

And I get,

File "./test.py", line 12, in __call__
super(Parent, self).__call__(someinfo)
AttributeError: 'super' object has no attribute '__call__'

And I can't figure out why, can somebody please help me with this?

回答1:

The super function takes the derived class as its first parameter, not the base class.

super(Person, self).__call__(someinfo)

If you need to use the base class, you can do it directly (but beware that this will break multiple inheritance, so you shouldn't do it unless you're sure that's what you want):

Parent.__call__(self, someinfo)