是否可以使用户定义的类型成为 Python 中内置类型的虚拟子类?我希望我的类被视为 int
的子类,但是我不想像这样直接继承:
class MyInt(int):
'''Do some stuff kind of like an int, but not exactly'''
pass
从那时起,无论我是否愿意,我的类(class)实际上都变得不可变了。例如,由于 int
无法修改自身,因此无法使用 __iadd__
和 __isub__
等方法。我可以从 numbers.Integral
继承,但是当有人调用 isinstance(myIntObj, int)
或 issubclass(MyInt, int)
时,答案将为 False
。我知 Prop 有 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'>
关于python - 是否可以成为内置类型的虚拟子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25149315/