5

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

class MyInt(int):
    '''Do some stuff kind of like an int, but not exactly'''
    pass

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

registerAsParent(int, MyInt)

我环顾四周(在 python 文档中和一般在线),还没有找到任何接近我正在寻找的东西。我所要求的完全不可能吗?

4

1 回答 1

0

不确定您到底要做什么,因为您要问的是不可能的,因为原始类型本质上是不可变的。但是,您可以覆盖__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'>

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

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

class MyInt(int):
    def __iadd__(self, other):
        return self.__class__(self - other)

因此,如果我们有另一个子类。

>>> class MyOtherInt(MyInt):
...     def __iadd__(self, other):
...         return self.__class__(self + other)
... 
>>> i = MyOtherInt(4)
>>> i += 4
>>> i
8
>>> type(i)
<class '__main__.MyOtherInt'>
于 2014-08-05T22:43:33.147 回答