2012-01-10 135 views
5

如何以编程方式访问Python中方法的默认参数值?例如,在下面在Python中访问默认参数值

def test(arg1='Foo'): 
    pass 

我怎么能访问字符串'Foo'test

+1

删除您能否提供一个例子证明你为什么会想这样做? – Kevin 2012-01-10 16:17:23

+0

你的意思是不只是输入'arg1'? – 2012-01-10 16:18:53

+0

如果你在调用'test'时不提供'arg1',那么'arg1'将默认为''Foo'' – TyrantWave 2012-01-10 16:21:37

回答

14

他们有s在test.func_defaults

+0

+1:这个!有用。 – 2012-01-10 16:22:27

2

里卡多卡德尼斯是在正确的轨道上。其实 内部test会变得更加棘手。该inspect模块将进一步得到你,但它会是丑陋:Python code to get current function into a variable?

事实证明,你可以参考test里面的函数:

def test(arg1='foo'): 
    print test.__defaults__[0] 

会打印出foo。但指的test只会工作,只要test实际上定义:

>>> test() 
foo 
>>> other = test 
>>> other() 
foo 
>>> del test 
>>> other() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in test 
NameError: global name 'test' is not defined 

所以,如果你打算在周围路过这个功能,你可能真的要离开了inspect路线:(

+0

我也有这种印象,事实证明,'测试'是在'测试'的本地范围内,正如里卡多对我的答案的评论中指出的那样。 – 2012-01-10 16:29:07

+0

很高兴知道!更新了我的答案以反映这一点! – 2012-01-10 16:35:33

+1

如果我们做'def test2():打印locals(),'\ n \ n',globals()',我们可以看到'test2'是全局变量,并且本地没有任何东西。 – 2016-08-10 04:28:39

0

这是不是很优雅(的话),但你想要做什么:

def test(arg1='Foo'): 
    print(test.__defaults__) 

test(arg1='Bar') 

与Python 3.x的太工程

+2

为什么'globals()'? 'test'在本身的范围内,不需要这个。 – 2012-01-10 16:24:32

+0

@RicardoCárdenes,你说得对。我不知道,谢谢。现在修复它。 – 2012-01-10 16:27:42

4

tored考虑:

def test(arg1='Foo'): 
    pass 

In [48]: test.func_defaults 
Out[48]: ('Foo',) 

.func_defaults为您提供了默认值,作为一个序列,以便参数出现在你的代码。

显然,func_defaults可能已经在Python 3

+4

我认为'func_defaults'只适用于Python 2.x. '__defaults__'似乎可以在Python 2.7和3.2上运行。 – 2012-01-10 16:25:54

+0

@RobWouters:很高兴知道,尽管我从不使用python 3。 – Marcin 2012-01-10 16:27:21