您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python的coerce()用来做什么?

Python的coerce()用来做什么?

它是早期python留下的,它基本上使一个元组成为相同的基础数字类型,例如

>>> type(10)
<type 'int'>
>>> type(10.0101010)
<type 'float'>
>>> nums = coerce(10, 10.001010)
>>> type(nums[0])
<type 'float'>
>>> type(nums[1])
<type 'float'>

它还允许对象在旧类中像数字一样工作 (这里用法一个不好的例子是…)

>>> class bad:
...     """ Dont do this, even if coerce was a good idea this simply
...         makes itself int ignoring type of other ! """
...     def __init__(self, s):
...             self.s = s
...     def __coerce__(self, other):
...             return (other, int(self.s))
... 
>>> coerce(10, bad("102"))
(102, 10)
python 2022/1/1 18:29:37 有190人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶