Python中函数的'类型'的内置名称是什么?

0 投票
4 回答
671 浏览
提问于 2025-04-15 14:23

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

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

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

更多详情请查看http://www.finalcog.com/python-memoise-memoize-function-type.

谢谢,

Chris.

4 个回答

1

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

函数。

“有没有办法避免创建这个lambda函数,以便获取一般函数的类型?”

有的,可以用types.FunctionType。或者直接用type(anyfunction)。

如果你是在问怎么去掉lambda(不过再读一遍我发现你可能不是这个意思),你可以定义一个普通的函数来代替lambda。

所以,不用:

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

你可以这样做:

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

你应该放弃在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

或者你可以直接试着调用它,然后捕捉可能出现的错误!

6

你可以使用 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 类型的默认构造器。

撰写回答