我正在寻找一种方法来检查给定函数在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!
谢谢。
你应该用^{} 。
您可以使用:
这不会确认可变长度参数,例如:
^{} 模块允许您检查函数的参数。这个问题在堆栈溢出时被问过几次;请尝试搜索其中的一些答案。例如:
Getting method parameter names in python
相关问题 更多 >
编程相关推荐