簡體   English   中英

Python:將函數以及參數分配給變量

[英]Python: Assigning function along with parameters to a variable

def test(name):
    print "name:", name

func = test
func("testing") # it works, as I know that the function test accepts one parameter.

我的問題是,根據情況,“測試”是否具有不同數量的參數,“功能”如何知道要傳遞的參數數量以及這些參數的名稱是什么?

對不起,如果我不清楚。 這樣可以使場景更加清晰。

我有一個函數調度器。

testcase_obj  = testcase() # A object of a class    
if command.startswith("test1"):    
    output = exec_test1()    
elif command.startswith("do_test"):    
    output = exec_do_test(testcase_obj)

現在,我想在用戶在執行腳本時發送選項時包裝一個函數。 我將上面的代碼更改為:

testcase_obj  = testcase() # A object of a class    
if command.startswith("test1"):    
    func = exec_test1() # Mistake, this should be func = exec_test1
elif command.startswith("do_test"):    
    func = exec_do_test(testcase_obj) # I don't know how assign exec_do_test along
                                      # with its parameter to 'func'. I don't want to
                                      # to call exec_to_test.

if option_given:    
    func = wrapper_func(func)    
    output = func() # At this point I don't how many parameters that "func" takes.

說出func = testfunc 只是test另一個名字 因此,您以與test完全相同的方式調用func ,並且如果您給func錯誤數量的參數,您將得到TypeError ,就像您未正確調用test

有關其他語言中的變量與Python中的名稱之間的區別的更多信息,請參見類似Pythonista的代碼

嘗試inspect模塊

import inspect
inspect.getargspec(func).args

會給:

['name']

會是一樣的。

func只是要測試的別名,而不是調用test的函數

如果“ test”采用可變數量的參數,則將其分配給“ func”。 我想知道“ func”有多少個參數。 內省(dir(func))將不會顯示“ func”可以接受多少個參數。

func不是函數。 它只是指向稱為test的函數的別名。 因此, func不能采用與test不同數量的參數,因為func 並不是一個函數,只是一個指向一個的名稱 您可以驗證以下內容:

>>> def test(arg1):
...    print 'test was given ',arg1
...
>>> func = test
>>> test.func_name
'test'
>>> func.func_name
'test'
>>> id(func)
3075004876L
>>> id(test)
3075004876L
>>> inspect.getargspec(func).args
['arg1']
>>> inspect.getargspec(test).args
['arg1']

是的,如果您給函數提供默認值,則有一種方法。

def test(name="default",hi=0):
    print "name:", name,hi

func = test
func("testing")
func("testing",6) 
func(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM