Python 如何确定将某些内容转换为哪种类型?

How does Python determine which type to cast something to?

假设我有以下内容:

x = "0"
y = 0
if x == y:
    print "You're winner!"

Python 会将 x 转换为 int,或将 y 转换为字符串?有什么办法可以控制这种行为吗?

不会发生任何转换。 xy 不相等,因为它们是不同的类型。如果你想控制相等性测试,你可以在你的对象上实现 "magic" __eq__ 方法。没有隐式转换功能。

Python 是一种强类型语言。除了 float 类型和涉及算术的 int 类型的少数例外,Python 不转换类型。

它也不会转换;它只会决定它们不相等。

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


请注意,仅仅因为 python 不为您做任何类型转换,各种对象 可能 。在这种情况下,所有的魔法都在 intstr__eq__ 方法中。当python看到:

a == b

它将尝试:

a.__eq__(b)

如果 returns NotImplemented,它将尝试 b.__eq__(a)。否则,a.__eq__(b) 的 return 值将被 return 编辑并用作比较结果。显然,对于其他类型的比较(__gt____lt____le__ 等)也有类似的 "dunder" 方法。

很少有内置对象允许与不同类型进行比较——事实上,我能想到的唯一允许这些恶作剧的内置对象是 intfloat 因为大多数人期望 1.0 == 1True...

另请注意(为了相等)大多数默认比较 return 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

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()

是的,您可以执行以下操作: 1. 将 x 转换为 int:

x = "0"
y = 0
if int(x) == y:
    print "You're winner!"
  1. y 转换为 str:

    x = "0" y = 0 if int(x) == y: print "You're winner!"