简体   繁体   English

Python:覆盖 __int__

[英]Python: overwrite __int__

A working solution, which returns integers, was given in Overload int() in Python .在 Python 的 Overload int() 中给出了一个返回整数的工作解决方案。

However, it works only for returning int , but not float or let's say a list:但是,它仅适用于返回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)

Thus t.__int__() works, but int(t) gives TypeError: __int__ returned non-int (type list) .因此t.__int__()有效,但int(t)给出TypeError: __int__ returned non-int (type list)

Thus, is there a possibility to fully overwrite int , maybe with __getattribute__ or metaclass ?因此,是否有可能完全覆盖int ,可能使用__getattribute__metaclass

The __int__ , __float__ , ... special methods and various others do not overwrite their respective type such as int , float , etc. These methods serve as hooks that allow the types to ask for an appropriate value. __int____float__ 、 ... 特殊方法和其他各种方法不会覆盖它们各自的类型,例如intfloat等。这些方法用作允许类型请求适当值的钩子。 The types will still enforce that a proper type is provided.这些类型仍将强制提供正确的类型。

If required, one can actually overwrite int and similar on the builtins module.如果需要,实际上可以在builtins模块上覆盖int和类似内容。 This can be done anywhere, and has global effect.这可以在任何地方进行,并具有全球影响。

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

Note that replacing builtin types may violate assumptions of code about these types, eg that type(int(x)) is int holds true.请注意,替换内置类型可能会违反关于这些类型的代码假设,例如type(int(x)) is int成立。 Only do so if absolutely required.只有在绝对需要时才这样做。

This is an example of how to replace int(...) .这是如何替换int(...)的示例。 It will break various features of int being a type, eg checking inheritance, unless the replacement is a carefully crafted type.它将破坏int类型的各种特性,例如检查 inheritance,除非替换是精心设计的类型。 A full replacement requires emulating the initial int type, eg via custom subclassing checks , and will not be completely possible for some builtin operations.完全替换需要模拟初始int类型,例如通过自定义子类检查,并且对于某些内置操作来说是不可能的。

From the doc of __int__来自__int__的文档

Called to implement the built-in functions complex(), int() and float().调用以实现内置函数 complex()、int() 和 float()。 Should return a value of the appropriate type.应该返回适当类型的值。

Here your method return a list and not an int , this works when calling it explictly but not using int() which checks the type of what is returned by the __int__在这里,您的方法返回一个list而不是int ,这在显式调用它时有效,但不使用int()检查__int__返回的类型


Here is a working example of what if could be, even if the usage if not very pertinent这是一个可行的例子,即使使用不是很相关

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python如何读取()并转换为__int__ - Python how to read() and convert to __int__ 适用于Python的__int __()的Java对象方法: - Java object method for Python's __int__(): Python 3中的__int__和__index__方法有什么区别? - What is the difference between the __int__ and __index__ methods in Python 3? MLKNN - __int__() 采用 1 个位置参数,但 2 个是使用 fit 方法给出的 - MLKNN - __int__() takes 1 positional argument but 2 were given with fit method Fraction 对象没有 __int__ 但 int(Fraction(...)) 仍然有效 - Fraction object doesn't have __int__ but int(Fraction(...)) still works 第11行:AttributeError:列表实例没有属性'__index__'或'__int__' - Line 11: AttributeError: list instance has no attribute '__index__' or '__int__' Google storage.Client 抛出 .__int__ 错误:接受 2 个位置参数,但给出了 3 个 - Google storage.Client throwing .__int__ error: takes 2 positional arguments but 3 were given 为什么我的 class 不是由“def __int__”或“def _init_”初始化? 为什么我会收到“不接受参数”类型错误或 AttributeError? - Why isn't my class initialized by "def __int__" or "def _init_"? Why do I get a "takes no arguments" TypeError, or an AttributeError? 在python中覆盖{} - Overwrite {} in python 提取元组并使用int迭代覆盖 - extract tuple and overwrite with int iteration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM