2014-02-26 48 views
0

我有這個示例代碼和nee可以打印出例如第二個論點的位置,我該怎麼做?如何打印位置參數

def fun(a, b, c): 
    d = locals() 
    e = d 
    print (e) 
    print (locals()) 

fun(None, 2, None) 
+0

我的編輯按鈕是不是一些未知的原因工作。我想編輯這個Q來閱讀;調用一個爭論位置,如fun [1](位置2等)。你可以調用一個字符串字符位置的方式 – user3346746

回答

0

print(b) ......或者我不明白這個問題。

更新:如果您的意思是要了解參數的名稱,您可能需要使用名爲inspect的標準模塊。請嘗試以下操作:

#!python3 
import inspect 

def fun(a, b, c): 
    d = locals() 
    e = d 
    print (e) 
    print (locals()) 

    # Here for observing from inside. 
    argspec = inspect.getfullargspec(fun) 
    print(argspec.args) 
    for arg in argspec.args: 
     print('argument', repr(arg), '=', repr(d[arg])) 

    # You can use indexing of the arg names if you like. Then the name 
    # is used for looking in locals() -- here you have it in d. 
    args = argspec.args 
    print(d[args[0]])  
    print(d[args[1]])  
    print(d[args[2]])  

fun(None, 2, None) 

# Here for observing from outside. 
argspec = inspect.getfullargspec(fun) 
print(argspec.args) 

for n, arg in enumerate(argspec.args, 1): 
    print('argument', n, 'is named', repr(arg)) 

您應該注意以下幾點:

{'a': None, 'b': 2, 'c': None} 
{'d': {...}, 'e': {...}, 'a': None, 'b': 2, 'c': None} 
['a', 'b', 'c'] 
argument 'a' = None 
argument 'b' = 2 
argument 'c' = None 
None 
2 
None 
['a', 'b', 'c'] 
argument 1 is named 'a' 
argument 2 is named 'b' 
argument 3 is named 'c' 

看到該文檔http://docs.python.org/3.3/library/inspect.html#inspect.getfullargspec

+0

謝謝,我需要一個代碼:for fun [1](position 2 etc)中的參數。我想通向所有的位置,而不是爭論 – user3346746