me_*_*and 46 python inheritance subclass python-2.5
我有兴趣在int
Python 中继承内置类型(我使用的是2.5版),但是在初始化工作时遇到了一些麻烦.
这是一些示例代码,应该是相当明显的.
class TestClass(int):
def __init__(self):
int.__init__(self, 5)
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用它时,我得到:
>>> a = TestClass()
>>> a
0
Run Code Online (Sandbox Code Playgroud)
在哪里我期待结果5
.
我究竟做错了什么?到目前为止,谷歌并没有太大的帮助,但我不确定我应该寻找什么
Anu*_*yal 65
int
是不可变的,所以你不能在创建后修改它,__new__
而是使用它
class TestClass(int):
def __new__(cls, *args, **kwargs):
return super(TestClass, cls).__new__(cls, 5)
print TestClass()
Run Code Online (Sandbox Code Playgroud)
虽然正确,但目前的答案可能并不完整.
例如
a = TestClass()
b = a - 5
print type(b)
Run Code Online (Sandbox Code Playgroud)
将b显示为整数,您可能希望它是TestClass.
这是一个改进的答案
class positive(int):
def __new__(cls, value, *args, **kwargs):
if value < 0:
raise ValueError("positive types must not be less than zero")
return super(cls, cls).__new__(cls, value)
def __add__(self, other):
res = super(positive, self).__add__(other)
return self.__class__(max(res, 0))
def __sub__(self, other):
res = super(positive, self).__sub__(other)
return self.__class__(max(res, 0))
def __mul__(self, other):
res = super(positive, self).__mul__(other)
return self.__class__(max(res, 0))
def __div__(self, other):
res = super(positive, self).__div__(other)
return self.__class__(max(res, 0))
def __str__(self):
return ("%d" % int(self))
def __repr__(self):
return ("positive(%d)" % int(self))
Run Code Online (Sandbox Code Playgroud)
现在进行同样的测试
>>> a = positive(10)
>>> b = a - 9
>>> print(type(b))
<class '__main__.positive'>
Run Code Online (Sandbox Code Playgroud)
更新:
添加了repr和str示例,以便新类正确打印自己.也改为Python 3语法,即使OP使用Python 2,也要保持相关性.