Reputation: 43
i have seen many posts that describe how to call base class function is called inside a derived class function using the super keyword.I want to call a base class overloaded function globally using a derived class object.
class a:
def __init__(self):
self.x=45
def fun(self):
print "fun in base class"
class b(a):
def __init__(self):
self.y=98
def fun(self):
print "fun in derived class"
objb=b()
objb.fun()#here i want to call the base class fun()
Upvotes: 0
Views: 2780
Reputation: 221
Input:
objb = b()
super(b, objb).fun()
Output:
fun in base class
Edit:
As mentionned in comment below, in Python 2.7+ you need to declare class a(object)
for this to work. This comes from a historical evolution of classes in Python, with this solution being functional for "new-style" classes only, i.e. for classes inheriting from object
. In Python 3.x however, all classes are "new-style" by default, meaning you don't have to perform this small addition.
Upvotes: 1
Reputation: 25769
If you really want to call the 'base' function that works on old-style classes (classes that don't extend object
) you can do it like:
objb = b()
a.fun(objb) # fun in base class
Or if you don't know the base/parent class, you can 'extract' it from the instance itself:
objb = b()
objb.__class__.__bases__[0].fun(objb) # fun in base class
But save yourself some trouble and just extend your base classes from object
so you can use the super()
notation instead of doing bases acrobatics.
Upvotes: 1