是否可以使用户定义的类型成为Python中内置类型的虚拟子类?我希望我的班级被视为以下类别的子类int
, 但是,我don't想像这样直接继承:
class MyInt(int):
'''Do some stuff kind of like an int, but not exactly'''
pass
从那时起,我的类实际上变得不可变,无论我是否愿意。例如,不可能使用类似的方法__iadd__
and __isub__
since int
没有办法修改自己。我可以继承自numbers.Integral
,但是当有人打电话时isinstance(myIntObj, int)
or issubclass(MyInt, int)
答案将是False
。我知道具有 ABCMeta 元类的类可以使用该方法register
将类注册为并非真正继承自它们的虚拟基类。有没有办法用内置类型来做到这一点?就像是:
registerAsParent(int, MyInt)
我环顾四周(无论是在 python 文档中还是在网上),但还没有找到任何接近我正在寻找的东西。我所要求的完全不可能吗?
不确定您到底想要做什么,因为您所要求的是不可能的,因为原始类型本质上是不可变的。但是你可以覆盖__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'>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)