如何在Python中重新定义函数?

12 投票
5 回答
27515 浏览
提问于 2025-04-16 04:01

我在某个模块里有一个函数,我想在运行时重新定义这个函数(也就是模拟一下),主要是为了测试。根据我的理解,在Python中,定义一个函数其实就是给它一个名字,就像给一个变量赋值一样(模块的定义本身也是一种函数的执行)。我想在测试用例的准备阶段做这个操作,而我想重新定义的函数在另一个模块里。请问怎么写这个语法呢?

举个例子,假设'module1'是我的模块,'func1'是我的函数,在我的测试用例里我尝试了这个(但没有成功):

import module1

module1.func1 = lambda x: return True

5 个回答

2

只需要把一个新的函数或者简单的函数(也叫lambda)赋值给旧的名字就可以了:

>>> def f(x):
...     return x+1
... 
>>> f(3)
4
>>> def new_f(x):
...     return x-1
... 
>>> f = new_f
>>> f(3)
2

当一个函数来自其他模块时,这种方法也能正常工作:

### In other.py:
# def f(x):
#    return x+1
###

import other

other.f = lambda x: x-1

print other.f(1)   # prints 0, not 2
5

在编程中,有时候我们需要在代码里使用一些特定的符号或者字符,这些符号可能会影响代码的运行。比如,某些符号在代码中有特殊的意义,像是用来表示开始或结束某个操作的。

当我们在写代码时,如果不小心把这些符号用错了,可能会导致程序出错,或者根本无法运行。因此,了解这些符号的用法和意义是非常重要的。

有些编程语言会提供一些工具或者方法,帮助我们处理这些特殊符号,确保代码能够顺利运行。掌握这些工具,可以让我们的编程更加顺利。

import foo

def bar(x):
    pass

foo.bar = bar
13
import module1
import unittest

class MyTest(unittest.TestCase):
    def setUp(self):
        # Replace othermod.function with our own mock
        self.old_func1 = module1.func1
        module1.func1 = self.my_new_func1

    def tearDown(self):
        module1.func1 = self.old_func1

    def my_new_func1(self, x):
        """A mock othermod.function just for our tests."""
        return True

    def test_func1(self):
        module1.func1("arg1")

很多模拟库提供了工具来进行这种模拟,你应该去了解一下它们,因为这些工具可能会给你很大的帮助。

撰写回答