Python 中的强制转换和强制转换有什么区别?
在 Python 文档和邮件列表中,我看到值有时是“强制转换”的,有时是“强制转换的”。
In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
演员阵容很明确。强制是隐含的。
Python 中的示例如下:
Cast 实际上仅出现在 C FFI 中。在 C 或 Java 中通常称为转换的内容在 Python 中称为转换,尽管它由于与其他语言的相似性而经常被称为转换。在我使用过的几乎所有语言(包括 python)中 强制 是隐式类型改变。
Cast is explicit. Coerce is implicit.
The examples in Python would be:
Cast really only comes up in the C FFI. What is typically called casting in C or Java is referred to as conversion in python, though it often gets referred to as casting because of its similarities to those other languages. In pretty much every language that I have experience with (including python) Coercion is implicit type changing.
我认为“强制转换”不应该用于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 dox+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.