Python 2 中比较类型有什么作用?
What does comparing types do in Python 2?
考虑这段代码:
class class1:
pass
class class2:
pass
class1 > class2
在 Python 3 中,我(正确地)收到此错误
TypeError: '>' not supported between instances of 'type' and 'type'
Python 2 发生了什么?
>>> class1 > class2
False
>>> class2 > class1
True
>>>
正如@user2864740 在评论中所说:
在Python 3、根据documentation,
The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number, the objects are of different types that cannot be compared, or other cases where there is no defined ordering.
在Python2,
The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
因为class都是同一类型(types.ClassType
),class1 < class2
将取决于两个class对象的内存地址恰好是什么。
考虑这段代码:
class class1:
pass
class class2:
pass
class1 > class2
在 Python 3 中,我(正确地)收到此错误
TypeError: '>' not supported between instances of 'type' and 'type'
Python 2 发生了什么?
>>> class1 > class2
False
>>> class2 > class1
True
>>>
正如@user2864740 在评论中所说:
在Python 3、根据documentation,
The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number, the objects are of different types that cannot be compared, or other cases where there is no defined ordering.
在Python2,
The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number. CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
因为class都是同一类型(types.ClassType
),class1 < class2
将取决于两个class对象的内存地址恰好是什么。