Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling parent's __call__ method within class

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?

like image 372
Jan Vorcak Avatar asked Oct 18 '11 11:10

Jan Vorcak


People also ask

How do you call a parent class method?

Calling Parent class Method Well this can done using Python. You just have to create an object of the child class and call the function of the parent class using dot(.) operator.

What is the __ call __ method?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

Can you call a parent class method from child class object?

You can't. Inside class Child you can call super. m1(), but what you want isn't possible. here object is of type child1,and refernce is of type parent1.

What is __ class __ in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .


1 Answers

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)
like image 155
Petr Viktorin Avatar answered Oct 03 '22 08:10

Petr Viktorin