是否有可能成为内置类型的虚拟子类?

ees*_*ada 5 python inheritance subclass abc

是否可以使用户定义的类型成为Python中内置类型的虚拟子类?我希望我的类被视为 的子类int,但是我想像这样直接继承:

class MyInt(int):
    '''Do some stuff kind of like an int, but not exactly'''
    pass
Run Code Online (Sandbox Code Playgroud)

从那时起,我的类实际上变得不可变,无论我是否愿意。例如,不可能使用像__iadd__和 这样的方法__isub__,因为int无法修改自身。我可以继承numbers.Integral,但是当有人打电话时isinstance(myIntObj, int)或者issubclass(MyInt, int)会得到答复False。据我所知,具有 ABCMeta 元类的类可以使用该方法register将类注册为不真正从它们继承的虚拟基类。有没有办法用内置类型来做到这一点?就像是:

registerAsParent(int, MyInt)
Run Code Online (Sandbox Code Playgroud)

我环顾四周(无论是在 python 文档中还是在网上),但还没有找到任何接近我正在寻找的东西。我所要求的完全不可能吗?

met*_*ter 1

不确定您到底想要做什么,因为您所要求的是不可能的,因为原始类型本质上是不可变的。但是,您可以覆盖__iadd__等以返回您想要的类型的结果。请注意,为了戏剧性,我颠倒了符号(用-代替+)。

>>> class MyInt(int):
...     def __iadd__(self, other):
...         return MyInt(self - other)
...     def __add__(self, other):
...         return MyInt(self - other)
... 
>>> i = MyInt(4)
>>> i += 1
>>> type(i)
<class '__main__.MyInt'>
>>> i
3
>>> i + 5
-2
>>> type(i + 5)
<class '__main__.MyInt'>
Run Code Online (Sandbox Code Playgroud)

冲洗并重复其余的魔术方法,无论如何您都需要这样做才能拥有 int 的“正确”子类(即使“虚拟”用户可能期望它们以某种方式运行)。

哦,是的,为了可扩展性(好像这还不算疯狂),请使用self.__class__结果

class MyInt(int):
    def __iadd__(self, other):
        return self.__class__(self - other)
Run Code Online (Sandbox Code Playgroud)

所以如果我们有另一个子类。

>>> class MyOtherInt(MyInt):
...     def __iadd__(self, other):
...         return self.__class__(self + other)
... 
>>> i = MyOtherInt(4)
>>> i += 4
>>> i
8
>>> type(i)
<class '__main__.MyOtherInt'>
Run Code Online (Sandbox Code Playgroud)