python - 如何继承和覆盖第三方类方法以扩展其功能?
问题描述
我需要覆盖来自第三方模块的类方法,我们将调用它foo
。foo
有一个方法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()
方法。有没有办法可以中断正常的过程来调用我的方法?
解决方案
在此处关注这篇文章: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
推荐阅读
- python - 使用 pandas 按时间顺序“dd.mm.yyyy”放置数据框
- azure - 哪些 Azure SQL 产品允许我部署 SSIS 包?
- python - 如何从数据框的每个类别中迭代和采样?
- java - 如何在 onComplete 中添加 TOAST 消息,我是 Android Studio 的初学者,我对 java 不太了解
- javascript - 如何让 puppeteer 使用 Firebase 函数?
- angular - Ionic Back Button - 如何触发动作,在 TypeScript 中扩展一个类
- python - 使用 python 处理 PEM 文件进行 SSL 连接
- java - JDK 1.8 或更高版本与 Cordova 的 Java 11 要求检查失败
- c# - Azure Functions:如何使用 Blob 触发器管理持久函数?
- sql - 转换行中的列并获取postresql中同一列的不同值的计数