在python中,函数是一个对象吗?

Jon*_*tes 5 python oop function python-2.7

理解这种行为有点难:

def a():
   pass


type(a)
>> function
Run Code Online (Sandbox Code Playgroud)

如果typea就是function,是什么typefunction

type(function)
>> NameError: name 'function' is not defined
Run Code Online (Sandbox Code Playgroud)

又为何typetype距离atype

type(type(a))
>> type
Run Code Online (Sandbox Code Playgroud)

最后一个:如果aobject,为什么我不能这样做:

isinstance(a, object)
>> True


class x(a):
   pass
TypeError: Error when calling the metaclass bases
    function() argument 1 must be code, not str
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ale*_*x W 5

任何函数的类型是<type 'function'>.函数类型<type 'type'>就像你一样type(type(a)).原因type(function)不起作用是因为type(function)试图获取被调用的未声明变量function的类型,而不是实际函数的类型(即function不是关键字).

您在类定义期间遇到元类错误,因为a它是类型的function,您不能在Python中子类化函数.

文档中有很多好的信息.