增加int对象 [英] increment int object

查看:104
本文介绍了增加int对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中有没有办法增加int对象,int似乎没有实现 __ iadd __ 所以+ = 1实际上返回一个新对象

Is there a way in python to increment int object in place, int doesn't seem to implement __iadd__ so += 1 actually returns a new object

>>> n=1
>>> id(n)
9788024
>>> n+=1
>>> id(n)
9788012

我想要的是n保持指向同一个对象。

What I want is n to remain pointing to same object.

目的:我有从int派生的类,我想为该类实现C类型'++ n'运算符

Purpose: I have class derived from int and I want to implement C type '++n' operator for that class

结论:好的,因为int是不可变的,没有办法,看起来我将不得不写自己的类这样的东西

Conclusion: ok as int is immutable there is no way, looks like i will have to write my own class something like this

class Int(object):
    def __init__(self, value):
        self._decr = False
        self.value = value

    def __neg__(self):
        if self._decr:
            self.value -= 1
        self._decr = not self._decr
        return self

    def __str__(self):
        return str(self.value)

    def __cmp__(self, n):
        return cmp(self.value, n)

    def __nonzero__(self):
        return self.value

n = Int(10)
while --n:
    print n


推荐答案

int是不可变的,所以如果你想要一个mutable int,你必须使用所有int方法构建自己的类

ints are immutable, so you'll have to build your own class with all the int's methods if you want a "mutable int"

这篇关于增加int对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆