簡體   English   中英

在Python中,函數“類型”的內置名稱是什么?

[英]What is the builtin name of the 'type' of functions, in Python?

什么Python內置<type 'function'>返回<type 'function'> type'function <type 'function'>

>>> type(lambda: None)
<type 'function'>

有沒有辦法避免創建此lambda函數,以便獲得一般的函數類型?

有關更多詳細信息,請參見http://www.finalcog.com/python-memoise-memoize-function-type

謝謝,

克里斯。

您應該能夠使用types.FunctionType來執行types.FunctionType的操作:

Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import types
    >>> help(types.FunctionType)

    Help on class function in module __builtin__:

    class function(object)
     |  function(code, globals[, name[, argdefs[, closure]]])
     |  
     |  Create a function object from a code object and a dictionary.
     |  The optional name string overrides the name from the code object.
     |  The optional argdefs tuple specifies the default argument values.
     |  The optional closure tuple supplies the bindings for free variables.

但是通常, def被認為是function類型的默認構造function

您應該擺脫Python中“類型”的想法。 大多數時候,您不想檢查某物的“類型”。 明確檢查類型容易損壞,例如:

>>> s1 = 'hello'
>>> s2 = u'hello'
>>> type(s1) == type(s2)
False

您要做的是檢查對象是否支持您要對其執行的任何操作。

如果要查看給定對象是否為函數,請執行以下操作:

>>> func = lambda x: x*2
>>> something_else = 'not callable'
>>> callable(func)
True
>>> callable(something_else)
False

或者只是嘗試調用它,然后捕獲異常!

“什么Python內置<type 'function'>返回<type 'function'> type'function <type 'function'> ?”

職能。

“是否有辦法避免創建此lambda函數,以便獲得一般的函數類型?”

是的,types.FunctionType。 或只是鍵入(任何功能)

如果您要問如何擺脫lambda(但重讀告訴我您可能不是),則可以定義一個函數而不是lambda。

所以代替:

>>> somemethod(lambda x: x+x)

你做

>>> def thefunction(x):
...     return x+x
>>> somemethod(thefunction)

內置不是function它們是: builtin_function_or_method 這不是命名的全部要點嗎?

您可以通過執行以下操作來獲得:

>>> type(len)
<class 'builtin_function_or_method'>

暫無
暫無

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

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