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"?
To call a parent's function from a child component, pass the function reference to the child component as a prop. Then you can call that parent's function from the child component like props. parentMethodName(). In the example code, we create a parent component named Parent.
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With