首页 > 解决方案 > 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

标签: pythonnumpy

解决方案


, __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类型,例如通过自定义子类检查,并且对于某些内置操作是不可能的。


推荐阅读