检查两个 python 函数(或方法)的兼容性 [英] Checking compatibility of two python functions (or methods)

查看:37
本文介绍了检查两个 python 函数(或方法)的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能检查两个 python 函数是否可以互换?例如,如果我有

Is there a possibility to check if two python functions are interchangeable? For instance, if I have

def foo(a, b):
    pass
def bar(x, y):
    pass
def baz(x,y,z):
    pass

我想要一个函数 is_compatible(a,b) 在传递 foo 和 bar 时返回 True,但在传递 bar 和 baz 时返回 False,所以我可以在实际调用之前检查它们是否可以互换任何一个.

I would like a function is_compatible(a,b) that returns True when passed foo and bar, but False when passed bar and baz, so I can check if they're interchangeable before actually calling either of them.

推荐答案

看看 inspect.getargspec():

获取名称和函数的默认值论据.四件事的元组是返回:(args, varargs, varkw,默认值).args 是一个列表参数名称(它可能包含嵌套的列表).varargs 和 varkw 是* 和 ** 参数的名称或没有任何.defaults 是一个默认的元组参数值或 None 如果有没有默认参数;如果这个元组有 n 个元素,它们对应于args 中列出的最后 n 个元素.

inspect.getargspec(func)

Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

在 2.6 版中更改:返回一个命名元组 ArgSpec(args, varargs,关键字,默认值).

这篇关于检查两个 python 函数(或方法)的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆