Subclassing int in Python

被刻印的时光 ゝ 提交于 2019-11-26 20:29:11

int is immutable so you can't modify it after it is created, use __new__ instead

class TestClass(int):
    def __new__(cls, *args, **kwargs):
        return  super(TestClass, cls).__new__(cls, 5)

print TestClass()
Jason Morgan

Though correct the current answers are potentially not complete.

e.g.

a = TestClass()
b = a - 5
print type(b)

Would show b as an integer, where you might want it to be a TestClass.

Here is an improved answer

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))

Now the same sort of test

>>> a = positive(10)
>>> b = a - 9
>>> print(type(b))
<class '__main__.positive'>

UPDATE:
Added repr and str examples so that the new class prints itself properly. Also changed to Python 3 syntax, even though OP used Python 2, to maintain relevancy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!