python,函数是对象吗?
考虑以下行为:
def a():
pass
type(a)
>> function
如果的类型是function
,那么function
的类型是什么呢?
type(function)
>> NameError: name 'function' is not defined
还有,为什么从得到的type
也是type
呢?
type(type(a))
>> type
isinstance(a, object)
>> True
class x(a):
pass
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str
2 个回答
3
在Python中,function
的类型是type
,而type
是Python里的基础元类。元类可以理解为“类的类”。你也可以把type
当成一个函数来使用,它可以告诉你一个对象的类型,不过这其实是历史遗留的用法。
types
模块提供了大部分内置类型的直接引用。
>>> import types
>>> def a():
... pass
>>> isinstance(a, types.FunctionType)
True
>>> type(a) is types.FunctionType
原则上,你甚至可以直接实例化types.FunctionType
这个类,动态创建一个函数,虽然我想不出有什么实际情况需要这样做:
>>> import types
>>> a = types.FunctionType(compile('print "Hello World!"', '', 'exec'), {}, 'a')
>>> a
<function a at 0x01FCD630>
>>> a()
Hello World!
>>>
你不能对一个函数进行子类化,这就是你最后一段代码失败的原因,不过其实你也不能对子类types.FunctionType
。