【问题标题】:Subclassing int in Python在 Python 中继承 int
【发布时间】:2011-03-15 09:06:33
【问题描述】:

我有兴趣继承 Python 中的内置 int 类型(我使用的是 v. 2.5),但在初始化工作时遇到了一些麻烦。

这是一些示例代码,应该相当明显。

class TestClass(int):
    def __init__(self):
        int.__init__(self, 5)

但是,当我尝试使用它时,我得到:

>>> a = TestClass()
>>> a
0

我希望结果是5

我做错了什么?到目前为止,Google 并没有太大帮助,但我不确定我应该搜索什么

【问题讨论】:

标签: python inheritance subclass python-2.5


【解决方案1】:

int 是不可变的,所以创建后不能修改,请改用__new__

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

print TestClass()

【讨论】:

    【解决方案2】:

    虽然正确,但当前的答案可能不完整。

    例如

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

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

    现在是同一种测试

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

    更新:
    添加了 reprstr 示例,以便新类正确打印自身。也更改为 Python 3 语法,尽管 OP 使用 Python 2,以保持相关性。

    【讨论】:

    • 我需要做什么才能使positive(10)*0.2 工作?
    • 这个例子的重点是对这个类的实例的操作返回同一个类的对象。将 0.2(浮点数)添加到正类型整数的结果不能是正类型,这是没有意义的。我建议使用@Anurag Uniyal 给出的示例,上面的结果对象可以是不同的类型。
    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2011-09-14
    • 2011-02-10
    • 1970-01-01
    • 2016-03-06
    相关资源
    最近更新 更多