gpt4 book ai didi

python - 有没有办法在 Python 中检查函数的签名?

转载 作者:太空狗 更新时间:2023-10-29 17:26:03 24 4
gpt4 key购买 nike

我正在寻找一种方法来检查给定函数在 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!

谢谢。

最佳答案

您可以使用:

import inspect
len(inspect.getargspec(foo_func)[0])

这不会确认变长参数,例如:

def foo(a, b, *args, **kwargs):
pass

关于python - 有没有办法在 Python 中检查函数的签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3534852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com