Python中强制转换和强制转换有什么区别? [英] What's the difference between casting and coercion in Python?

查看:74
本文介绍了Python中强制转换和强制转换有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python文档和邮件列表中,我看到值有时是强制转换"的,有时是强制的"的.

In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced".

推荐答案

我认为"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆