【问题标题】:Python: overwrite __int__Python:覆盖 __int__
【发布时间】:2020-04-05 12:22:31
【问题描述】:

Overload int() in Python 中给出了一个返回整数的有效解决方案。

但是,它仅适用于返回 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__metaclass

【问题讨论】:

  • 方法 __int__ 是一个 toInt 所以它应该返回一个 int 而不是一个列表
  • intstr等的想法是,它们调用底层的__int____str__,并进行这种类型检查。根据合同,str(..) 应该返回一个 string 的实例。
  • __int__ 不会覆盖int。该方法是int 在不理解其参数类型时使用的钩子。

标签: python numpy


【解决方案1】:

__int__, __float__, ... 特殊方法和其他各种方法不会覆盖它们各自的类型,例如intfloat 等。这些方法用作允许类型的钩子 要求一个适当的值。这些类型仍将强制提供正确的类型。

如果需要,实际上可以覆盖intbuiltins 模块上的类似内容。这可以在任何地方进行,并且具有全球影响。

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 类型,例如通过custom subclassing checks,并且对于某些内置操作将无法完全实现。

【讨论】:

  • 谢谢!一个聪明的黑客。
  • 现在,我还可以通过一些纯python函数来偷运numpy数组。因此矢量化int 的一种肮脏方式是import numpy as np; import builtins; builtins.int = lambda x: x.astype(np.int); int(np.array([1.5, 6.1]))
【解决方案2】:

来自__int__的文档

调用以实现内置函数complex()、int() 和float()。应该返回适​​当类型的值。

这里你的方法返回一个list而不是int,这在显式调用它时有效,但不使用int()检查__int__返回的内容的类型


这是一个可行的例子,说明 if 可能是什么,即使用法不是很相关

class Test:
    def __init__(self, mylist):
        self.mylist = mylist
    def __int__(self):
        return int(sum(self.mylist))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2020-06-16
    • 2012-02-01
    • 2011-10-17
    • 2016-01-14
    相关资源
    最近更新 更多