Python如何确定将某些类型转换为什么类型?

Are*_*res 2 python comparison casting

假设我有以下内容:

x = "0"
y = 0
if x == y:
    print "You're winner!"
Run Code Online (Sandbox Code Playgroud)

Python会转换x为int还是y字符串?有没有办法控制这种行为?

mgi*_*son 6

Python不会为你做任何类型转换.如果你想控制它,那么你应该是明确的.


请注意,仅仅因为python没有为你做任何类型转换,各种对象可能会.在这种情况下,所有的魔力是在__eq__对方法intstr.当python看到:

a == b
Run Code Online (Sandbox Code Playgroud)

它会尝试:

a.__eq__(b)
Run Code Online (Sandbox Code Playgroud)

如果返回NotImplemented,则会尝试b.__eq__(a).否则,将返回返回值a.__eq__(b)并将其用作比较结果.显然,有用于其它类型的比较类似的"dunder"的方法(__gt__,__lt__,__le__等).

很少有内置对象允许比较不同类型的-事实上,我能想到的把我的头顶部,让那些五花八门有心计的唯一内置对象intfloat因为大多数人想到1.0 == 1True...

另请注意(对于相等),False如果类型不匹配,则返回大多数默认比较.没有错误提出.对于其他的,更丰富的比较(例如__lt__,__gt__)的结果实际上取决于版本.Python2.x基于类型的订单.它保证了一致(但任意)的排序.

Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> '1' > 1
True
Run Code Online (Sandbox Code Playgroud)

Python3.x做了一个更聪明的事情,通过提出一个完全不允许它TypeError:

$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> '1' > 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
Run Code Online (Sandbox Code Playgroud)