python - 如何重写第三方库使用的方法

标签 python

这就是布局

some_function.py

def some_function():
    print("some_function")

some_library.py

from some_function import some_function

class A:
    def xxx(self):
        some_function()

main.py

from some_library import A
from some_function import some_function

def new_some_function():
    print("new_some_function")

if __name__ == '__main__':
    some_function = new_some_function
    a = A()
    a.xxx()

在类A中,方法xxx调用some_function,那么是否可以用其他东西覆盖它,而无需重新实现整个类?

最佳答案

我认为您正在寻找猴子修补(意味着在运行时动态更改类/模块)。这样您就不需要覆盖类 A 并按照其他评论的建议使用继承 - 您说过您不希望这样做,所以请尝试以下解决方案:

import some_class  # import like this or will not work (cos of namespaces)

def new_some_function():
   print("new_some_function")

if __name__ == '__main__':
    # Import and use like this, other ways of import will not work.
    # Because other way imports method to your namespace and then change it in your namespace,
    # but you need to change it in the original namespace
    some_class.some_function = new_some_function

这样就可以替换原来的方法,甚至其他类也会使用它。请注意,如果原始方法是类/实例方法,则需要使用适当的参数创建新函数,如下所示:

def new_some_function(self):
    # for instance methods, you may add other args, but 'self' is important

def new_some_function(cls):
    # for class methods, you may add other args, but 'cls' is important

关于python - 如何重写第三方库使用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52174419/

相关文章:

python - 迭代多索引 Pandas DataFrame 以按特定索引级别进行规范化

python - Celery 忽略 retry_backoff,而是重复重试 180 秒

python - pyqt5选项卡区域未填充整个可用空间

python - 如何预测 scikit-learn 中的时间序列?

python - 使用 sqlalchemy orm 从查询创建临时表

Python:为什么我的代码以全部大写结尾?

python - 遍历 Web 元素

python - 将 RGB 数组转换为 HSL

python - 优化列表理解以找到互质数对

python - pyside-uic 在哪里?