python - Python:覆盖 __int__
问题描述
在 Python中的 Overload int() 中给出了一个返回整数的有效解决方案。
但是,它仅适用于返回int
,而不适用于float
或者让我们说一个列表:
class Test:
def __init__(self, mylist):
self.mylist = mylist
def __int__(self):
return list(map(int, self.mylist))
t = Test([1.5, 6.1])
t.__int__() # [1, 6]
int(t)
因此t.__int__()
有效,但int(t)
给出了TypeError: __int__ returned non-int (type list)
.
因此,是否有可能完全覆盖int
,也许用__getattribute__
or metaclass
?
解决方案
, __int__
, __float__
... 特殊方法和其他各种方法不会覆盖它们各自的类型,例如int
,float
等。这些方法用作允许类型请求适当值的钩子。这些类型仍将强制提供正确的类型。
如果需要,实际上可以在模块上覆盖int
和类似。builtins
这可以在任何地方进行,并具有全球影响。
import builtins
# store the original ``int`` type as a default argument
def weakint(x, base=None, _real_int=builtins.int):
"""A weakly typed ``int`` whose return type may be another type"""
if base is None:
try:
return type(x).__int__(x)
except AttributeError:
return _real_int(x)
return _real_int(x, base)
# overwrite the original ``int`` type with the weaker one
builtins.int = weakint
请注意,替换内置类型可能会违反关于这些类型的代码假设,例如,这type(int(x)) is int
是正确的。只有在绝对需要时才这样做。
这是如何替换的示例int(...)
。它将破坏int
作为类型的各种特性,例如检查继承,除非替换是精心设计的类型。完全替换需要模拟初始int
类型,例如通过自定义子类检查,并且对于某些内置操作是不可能的。
推荐阅读
- node.js - 在带有 express 的 node.js 中,有没有办法即时更改链接的 url?
- excel - 在表中查找字符串并删除行
- c# - ImageResizer 最佳设置以获得最高质量
- java - 在 SELECT BIGQUERY 语句中测量大小(以字节为单位)
- java - why maven fails to build for this project
- python-3.x - 如何从 YOUTUBE API 获得 Python 响应
- module - 创建一个模块,在 Drupal 8 中使用包含字段图像的表单实现新的 fieldType
- sql - 我正在尝试在 SQL 中构建一个视图,该视图识别和分组具有连续日期范围的记录,并返回最早和最晚日期
- jquery - 如何使用 jquery 查询 url 参数?
- javascript - 如何使用图像制作响应式 3 行