python,函数是一个对象吗?

标签 python function oop python-2.7

鉴于以下行为:

    def a():
       pass


    type(a)
    >> function

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

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

为什么 a 中的 typetypetype

    type(type(a))
    >> type

最后:如果a是一个对象,为什么不能被继承?

    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'> .函数类型的类型是<type 'type'> ,就像你用 type(type(a)) 得到的一样.原因type(function)不起作用是因为type(function)正在尝试获取名为 function 的未声明变量的类型,而不是实际函数的类型(即 function 不是关键字)。

您在类定义期间收到元类错误,因为 a类型为 function还有你can't subclass functions in Python .

很多有用的信息 in the docs .

关于python,函数是一个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24707237/

相关文章:

r - 在 do.call 中指定函数的双冒号运算符

JavaScript 配置管理器类

Python 动画阴影 matplotlib

javascript - jquery 函数不会在第一次点击时工作

python - 如何在特定字符处拆分字符串并构建不同的字符串组合

php - 从另一个 PHP 函数调用 PHP 函数的逻辑错误

c# - 类可以在 C# 中使用别名吗?

c# - 在程序启动时实例化一个随机类

python - 在 python 中,如何让 urllib 将字符串中的多行识别为单独的 URL?

python - 在 Python 中创建假数据