代码之家  ›  专栏  ›  技术社区  ›  me_and

python中的子类化int

  •  40
  • me_and  · 技术社区  · 14 年前

    我对内建子类感兴趣 int 输入python(我使用的是v.2.5),但在初始化工作中遇到一些问题。

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

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

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

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

    我希望结果会是什么 5 .

    我做错什么了?到目前为止,谷歌并不是很有帮助,但我不确定我应该搜索什么

    2 回复  |  直到 14 年前
        1
  •  59
  •   Anurag Uniyal    7 年前

    int 是不可变的,因此在创建后不能修改它,请使用 __new__ 相反

    class TestClass(int):
        def __new__(cls, *args, **kwargs):
            return  super(TestClass, cls).__new__(cls, 5)
    
    print TestClass()
    
        2
  •  7
  •   Mike Williamson    6 年前

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

    例如

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

    更新:
    补充 再PR STR 示例,以便新类正确地打印自己。也改为python 3语法,尽管op 2使用python 2来维护相关性。