Python中,函数是一个对象吗?

5

考虑以下行为:

    def a():
       pass


    type(a)
    >> function

如果a的类型是function,那么function的类型是什么?
    type(function)
    >> NameError: name 'function' is not defined

And why does type of type from a is type?

    type(type(a))
    >> type

最后:如果 a 是一个 object ,为什么它不能被继承?
    isinstance(a, object)
    >> True

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

这些都看起来是正确的。你期望 type(function) 返回什么? - Cory Kramer
4
可能是什么是“一等对象”?的重复问题。 - g.d.d.c
2个回答

5
任何函数的类型是<type 'function'>。函数类型的类型是<type 'type'>,就像您使用type(type(a))一样。 type(function)不起作用的原因是因为它尝试获取名为function的未声明变量的类型,而不是实际函数的类型(即function不是关键字)。
在类定义期间出现元类错误的原因是a的类型为function,而您无法在Python中对函数进行子类化
文档中有很多好的信息可以参考

3
function 的类型是 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进行子类化。


如果我使用a = types.FunctionType(compile('return 0', '', 'exec'), {}, 'a'),为什么会出现SyntaxError: 'return' outside function的错误?另外请注意,在Python 3中,你的第二个例子应该是a = types.FunctionType(compile('print("Hello World!")', '', 'exec'), {"print": print}, 'a') - nbro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接