我正在使用一个 python 库,我需要在其中覆盖其中一个函数。我们将其命名为 module.py
:
def dump(nodes, args = 'bleh' ):
...validation checks
for node in nodes:
print(node, someother_args)
def print_node(node, someother_args):
...prints in some way i don't want
现在,我正在使用这个 dump
方法,我想用我自己的 print_node
方法覆盖 print_node
函数,因为我想打印它以不同的方式。最好的方法是什么?
最佳答案
您可以自己创建一个继承自预期模块的类,并以任何您想要的方式覆盖该函数。然后你可以使用你的对象而不是 module.py
。
class my_class(module):
def __init__(self, *args, **kwargs):
super(my_class, self).__init__(*args, **kwargs)
def dump(self):
# do stuff
正如您在评论中提到的,如果您的模块包含一堆函数,您最好在当前模块中定义新函数。然后您可以将其分配给该函数名称。
正如@Joran Beasley 也提到的,您可以执行以下操作
import my_file
my_file.dump = my_local_dump_fn
关于python - 如何覆盖 python 库的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553545/