这就是布局
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/