在Python中进行强制转换 [英] Casting vs. coercion in Python
问题描述
在Python文档和邮件列表中,我看到值有时是强制转换的,有时是强制的的。有什么不同?
In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced". What is the difference?
推荐答案
我认为 casting不应该用于Python;只有类型转换,而没有强制转换(在C意义上)。完成类型转换,例如通过 int(o)
将对象o转换为整数(实际上,整数对象是从o构造的)。强制转换发生在二进制操作的情况下:如果您执行 x + y
,并且x和y具有不同的类型,则在执行该操作之前将它们强制转换为单一类型。在2.x中,特殊方法 __ coerce __
允许对象控制其强制。
I think "casting" shouldn't be used for Python; there are only type conversion, but no casts (in the C sense). A type conversion is done e.g. through int(o)
where the object o is converted into an integer (actually, an integer object is constructed out of o). Coercion happens in the case of binary operations: if you do x+y
, and x and y have different types, they are coerced into a single type before performing the operation. In 2.x, a special method __coerce__
allows object to control their coercion.
这篇关于在Python中进行强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!