I have came around this question during an interview:
class Parent(object):
def A(self):
print \"in A\"
class Child(Parent):
def A(self):
As you see, methods of objects always have the self
parameter.
You can call objects methods as
C.A()
or equivalently, by explicitly passing the self
parameter, as:
Child.A(C)
In the second way, you can call also the method of the parent class using the C
instance:
Parent.A(C)
If you are looking for a general method to solve this (i.e. without knowing the name of the parent class), you can use super() and type():
super(type(C)).A(C)
However, super()
has a nice additional argument to specify an object instance, so you could write also:
super(type(C), C).A()
You can use super() builtin.
>>> super(Child, C).A()
in A
It is usually used to call super class implementation inside subclasses, but it is also allowed outside. Docs state:
Also note that super() is not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references.
Call the method on the class explicitly.
Parent.A(C)
Use a super
call passing the type
of child class and the desired instance object which is just C
:
super(type(C), C).A() # of the form super(class, obj) where class == Child and obj == C
Having instance C
we could get its base class and call its A()
:
C.__class__.__base__().A()