Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a parent method from outside the child

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"?

like image 223
rh0dium Avatar asked Feb 02 '17 23:02

rh0dium


People also ask

How do you call parent method from child method?

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.

Can child class access parent methods?

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.


1 Answers

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
like image 171
calico_ Avatar answered Oct 08 '22 17:10

calico_