在Python中,“类型”函数的内置名称是什么?

2024-06-16 16:59:20 发布

您现在位置:Python中文网/ 问答频道 /正文

什么Python内置函数返回<type 'function'>?在

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

有没有办法避免创建这个lambda函数,以获得函数的一般类型?在

有关详细信息,请参见http://www.finalcog.com/python-memoise-memoize-function-type。在

谢谢

克里斯。在


Tags: lambda函数comnonehttp类型wwwtype
3条回答

你应该摆脱Python中“类型”的概念。大多数时候你不想检查某个东西的“类型”。显式检查类型容易损坏,例如:

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

您要做的是检查对象是否支持您试图对其执行的任何操作。在

如果要查看给定对象是否为函数,请执行以下操作:

^{pr2}$

或者尝试调用它,然后捕捉异常!在

“什么Python内置函数返回<type 'function'>?”在

功能。在

有没有办法避免创建这个lambda函数,以便获得函数的一般类型在

是的,类型.函数类型. 或者只输入(anyfunction)

如果你在问如何去除lambda(但是重读后我发现你可能不是),你可以定义一个函数而不是lambda。在

所以不是:

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

你知道吗

^{pr2}$

您应该能够使用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类型的默认构造函数。在

相关问题 更多 >