2012-01-10 133 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