鉴于以下行为:
def a():
pass
type(a)
>> function
如果a
的类型是function
,那么function
的type
是什么?
type(function)
>> NameError: name 'function' is not defined
为什么 a
中的 type
的 type
是 type
?
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/