从孩子外部调用父方法

rh0*_*ium 2 python inheritance

我有一堆class对象都从基类继承。其中一些重写方法(save)并执行操作。对于这个特殊的用例,我想暂时不允许使用子save方法(如果存在),而是强制使用父save方法。

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()
Run Code Online (Sandbox Code Playgroud)

如何obj从孩子的外部调用父级保存,以使其打印“ Base Called”?

cal*_*co_ 6

您可以从父对象调用方法 super()

super(type(obj), obj).save()
Run Code Online (Sandbox Code Playgroud)

当我运行这个:

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()
Run Code Online (Sandbox Code Playgroud)

输出:

Base Called
Run Code Online (Sandbox Code Playgroud)