如何在Python的另一个函数中找出特定函数自变量的默认值? [英] How to find out the default values of a particular function's argument in another function in Python?

查看:243
本文介绍了如何在Python的另一个函数中找出特定函数自变量的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个像这样的函数:

Let's suppose we have a function like this:

def myFunction(arg1='a default value'):
  pass

我们可以使用自省来找出 myFunction()使用 myFunction.func_code.co_varnames ,但是如何找出默认值 arg1 (在上面的示例中为'默认值')?

We can use introspection to find out the names of the arguments that myFunction() takes using myFunction.func_code.co_varnames, but how to find out the default value of arg1 (which is 'a default value' in the above example)?

推荐答案

除了扎根于函数的属性之外,您还可以使用inspect模块创建一个稍微友好的界面:

As an alternative to rooting around in the attributes of the function you can use the inspect module for a slightly friendlier interface:

对于Python 3。 x解释器:

For Python 3.x interpreters:

import inspect
spec = inspect.getfullargspec(myFunction)

然后说明是一个 FullArgSpec 对象,其属性如 args 默认值

Then spec is a FullArgSpec object with attributes such as args and defaults:

FullArgSpec(args=['arg1'], varargs=None, varkw=None, defaults=('a default value',), kwonlyargs=[], kwonlydefaults=None, annotations={})

有些这些属性中的一部分在Python 2上不可用,因此如果必须使用旧版本 inspect.getargspec(myFunction)将为您提供类似的值,而无需使用Python 3功能( getargspec 也可在Python 3上使用,但自Python 3.0起已弃用,因此请不要使用它):

Some of these attributes are not available on Python 2 so if you have to use an old version inspect.getargspec(myFunction) will give you a similar value without the Python 3 features (getargspec also works on Python 3 but has been deprecated since Python 3.0 so don't use it):

import inspect
spec = inspect.getargspec(myFunction)

然后spec是一个 ArgSpec 对象,具有诸如 args defaults

Then spec is an ArgSpec object with attributes such as args and defaults:

ArgSpec(args=['arg1'], varargs=None, keywords=None, defaults=('a default value',))

这篇关于如何在Python的另一个函数中找出特定函数自变量的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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