[英]What function is func here? Where did it come from?
這是我的代碼:
def testit(func, *nkwargs, **kwargs):
try:
retval = func(*nkwargs, **kwargs)
result = (True, retval)
except Exception, diag:
result = (False, str(diag))
return result
def test():
funcs = (int, long, float)
vals = (1234, 12.34, '1234', '12.34')
for eachFunc in funcs:
print '-' * 20
for eachVal in vals:
retval = testit(eachFunc, eachVal)
if retval[0]:
print '%s(%s) =' % \
(eachFunc.__name__, `eachVal`), retval[1]
else:
print '%s(%s) = FAILED:' % \
(eachFunc.__name__, `eachVal`), retval[1]
if __name__ == '__main__':
test()
第三行func
的作用是什么。 我認為這是一個變量。 它是如何變成函數名的?
Python 函數是一流的對象。 這意味着您可以將這樣的對象分配給變量並將其傳遞給另一個函數。 執行def functionname(): ...
語句的行為將這樣一個對象分配給一個名稱(此處為functionname
):
>>> def foo(): return 42
...
>>> foo
<function foo at 0x107e9f0d0>
>>> bar = foo
>>> bar
<function foo at 0x107e9f0d0>
>>> bar()
42
所以表達式
funcs = (int, long, float)
接受 3 個內置函數並將它們放入一個元組中。 funcs[0]('10')
將返回整數對象10
,因為funcs[0]
是對int()
函數的另一個引用,所以funcs[0]('10')
會給你與int('10')
完全相同的結果int('10')
。
這些函數對象在循環中傳遞給testit()
函數:
for eachFunc in funcs:
print '-' * 20
for eachVal in vals:
retval = testit(eachFunc, eachVal)
所以eachFunc
綁定到函數對象的funcs
的元組引用,一個接一個。
testit()
將該函數對象作為func
參數,然后調用它:
def testit(func, *nkwargs, **kwargs):
try:
retval = func(*nkwargs, **kwargs)
所以這會從values
元組中對各種測試值調用int()
、 long()
和float()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.