我正在寻找一种方法来检查Python中给定函数所需的参数数量。目的是为了实现更健壮的方法,以便对我的类进行测试补丁。因此,我想要做类似于以下方式的操作:
class MyClass (object):
def my_function(self, arg1, arg2):
result = ... # Something complicated
return result
def patch(object, func_name, replacement_func):
import new
orig_func = getattr(object, func_name)
replacement_func = new.instancemethod(replacement_func,
object, object.__class__)
# ...
# Verify that orig_func and replacement_func have the
# same signature. If not, raise an error.
# ...
setattr(object, func_name, replacement_func)
my_patched_object = MyClass()
patch(my_patched_object, "my_function", lambda self, arg1: "dummy result")
# The above line should raise an error!
感谢。