Python内置返回<type 'function'>
?在Python中,“类型”函数的内建名称是什么?
>>> type(lambda: None)
<type 'function'>
是否有避免产生这种lambda函数,以获得的功能类型,一般的方法是什么?
有关更多详细信息,请参见http://www.finalcog.com/python-memoise-memoize-function-type。
谢谢,
Chris。
Python内置返回<type 'function'>
?在Python中,“类型”函数的内建名称是什么?
>>> type(lambda: None)
<type 'function'>
是否有避免产生这种lambda函数,以获得的功能类型,一般的方法是什么?
有关更多详细信息,请参见http://www.finalcog.com/python-memoise-memoize-function-type。
谢谢,
Chris。
你应该能够使用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
s它们是:builtin_function_or_method
。这不是命名的全部意义吗?
>>> type(len)
<class 'builtin_function_or_method'>
这是正确的,但它不回答问题。 – 2009-09-17 17:16:52
“什么Python内置返回<type 'function'>
?”
功能。
“是否有避免创建此lambda函数的方法,以便获得通用类型的函数?”
是的,types.FunctionType。如果你问的是如何摆脱lambdas(但重新读取告诉我你可能不是),你可以定义一个函数,而不是lambda。
所以不是:
>>> somemethod(lambda x: x+x)
你做
>>> def thefunction(x):
... return x+x
>>> somemethod(thefunction)
你应该从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 3.0中使用'hasattr(func,“func_code”)',或在Python> = 3.0中使用'hasattr(func,“__code __”)''。然而,'function'类非常特殊,我认为按类型检查它是有道理的。 – 2009-09-17 17:19:51
此外,请注意,函数类型和可调用函数之间存在差异,因为任何类的实例都可以调用。我无法确切知道OP的代码试图去理解一个可调用函数是否足以满足他的目的。 – 2009-09-17 17:22:10
我刚刚从你那里学到了callable()。 '很确定我会越来越多地使用它。谢谢! – jedmao 2011-01-15 04:23:11
为什么你需要知道函数的类型? – 2009-09-17 16:35:29