Reputation: 7032
I have a bunch of class
objects which all inherit from a base class. Some of them override a method (save
) and do stuff. For this particular use case I want to temporarily not allow the child save
method to be used (if it exists) but rather force the use of the parent save
method.
class BaseClass(object):
def save(self, *args, **kwargs):
print("Base Called")
class Foo(BaseClass):
def save(self, *args, **kwargs):
# do_stuff
print("Foo called")
return super(Foo, self).save(*args, **kwargs)
obj = Foo()
How can I call obj
parent save from outside the child such that it prints "Base Called"?
Upvotes: 17
Views: 6073
Reputation: 1221
You can call methods from an objects parent with super()
super(type(obj), obj).save()
When I run this:
class BaseClass(object):
def save(self, *args, **kwargs):
print("Base Called")
class Foo(BaseClass):
def save(self, *args, **kwargs):
# do_stuff
print("Foo called")
return super(Foo, self).save(*args, **kwargs)
obj = Foo()
super(type(obj), obj).save()
The output:
Base Called
Upvotes: 25