当我尝试在 Python 3
和 Python 2
中检查 class
声明的类型时,我得到了奇怪的结果,如下所示,
>>> #python 2.7.6
>>> class MyClass:
... pass
...
>>> type(MyClass)
<type 'classobj'>
>>> hasattr(MyClass, '__call__')
False
Python 2
中MyClass
的type
是classobj
,MyClass
有没有 __call__
属性。这是我所期望的。
>>> #python 3.3.3
>>> class MyClass:
... pass
...
>>> type(MyClass)
<class 'type'>
>>> hasattr(MyClass, '__call__')
True
但是,在 Python 3
中,MyClass
的 type
是 class 'type'
,并且 MyClass
具有 __call__
属性,尽管我没有在 MyClass
中声明它。
我猜原因是在Python 3
中,MyClass
是一个type
,而type
有__call__
属性,我说得对吗?为什么 Python 3
会像这样改变 type
函数的行为?
最佳答案
改变的是 3.x 中的所有类默认都是新式类。您的 Python 2 类没有继承自 object
,因此 Python 认为它是一个旧式类。
在 2.7.5 中:
>>> class MyClass(object):
... pass
...
>>> type(MyClass)
<type 'type'>
>>> hasattr(MyClass, '__call__')
True
关于python - Python 3 和 Python 2 之间 type() 和 hasattr() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21174596/