【问题标题】:python, is function an object?python,函数是对象吗?
【发布时间】:2014-09-02 15:21:57
【问题描述】:

鉴于以下行为:

    def a():
       pass


    type(a)
    >> function

如果a 的类型是function,那么functiontype 是什么?

    type(function)
    >> NameError: name 'function' is not defined

为什么来自atype 中的typetype

    type(type(a))
    >> type

最后:如果aobject,为什么不能被继承?

    isinstance(a, object)
    >> True

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

【问题讨论】:

标签: python function oop python-2.7


【解决方案1】:

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

您在类定义期间遇到元类错误,因为 a 的类型为 function 而您是 can't subclass functions in Python

大量有用的信息in the docs

【讨论】:

    【解决方案2】:

    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!
    >>>
    

    你不能子类化一个函数,这就是你最后一个 sn-p 失败的原因,但你不能子类 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')
    猜你喜欢
    • 2017-06-09
    • 2014-10-07
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2014-02-01
    • 1970-01-01
    相关资源
    最近更新 更多