首页 > 解决方案 > 如何继承和覆盖第三方类方法以扩展其功能?

问题描述

我需要覆盖来自第三方模块的类方法,我们将调用它foofoo有一个方法post()调用create_object()我想覆盖的另一个方法,并扩展它的功能:

foo.py

class Foo():
    def create_object():
        return 'Creating object 1'

    def post(self):
        result = self.create_object()

bar.py

class Bar(Foo):
    def create_object(self):
        return 'Creating object 2'

当调用foo'post()方法时,我希望它重定向到bar'create_object()方法。有没有办法可以中断正常的过程来调用我的方法?

标签: pythoninheritanceoverriding

解决方案


在此处关注这篇文章:https ://tryolabs.com/blog/2013/07/05/run-time-method-patching-python/

更新后的代码如下:

foo.py

class Foo():
    def create_object():
        return 'Creating object 1'

    def post(self):
        result = self.create_object()

bar.py

class Bar(Foo):

    def create_object(self):
        return 'Creating object 2'

    def run(self):
        Foo.create_object = self.create_object

推荐阅读