递增整数对象

16 投票
7 回答
17735 浏览
提问于 2025-04-15 12:56

在Python中,有没有办法直接在原地增加一个整数对象的值?因为整数(int)似乎没有实现 __iadd__ 这个方法,所以用 += 1 实际上是返回了一个新的对象。

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

我想要的是 n 仍然指向同一个对象。

目的:我有一个从整数(int)派生的类,我想为这个类实现 C 语言中的 '++n' 操作符。

结论:好吧,因为整数是不可变的,所以没有办法。看起来我得自己写一个类似这样的类。

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

7 个回答

6

如果你真的必须让这段代码运行,这里有个不太好的方法,就是一个实例方法可以向上移动一帧,并覆盖它自己在本地的条目。不过我不推荐这样做。(真的不推荐。我甚至不太明白这样做会有什么后果。旧的实例会怎样?我对帧的理解不够深……)其实,我发这个只是因为大家都说这是不可能的,但实际上这只是个非常糟糕的做法。;-)

import sys
class FakeInt(int):
    def __init__(self, *arg, **kwarg):
        self._decr = False
        int.__init__(self, *arg, **kwarg)
    def __neg__(self):
        if self._decr:

            upLocals = sys._getframe(1).f_locals
            keys, values = zip(*upLocals.items())
            i = list(values).index(self)

            result = FakeInt(self-1)
            upLocals[keys[i]]=result

            return result
        self._decr = not self._decr
        return self

A = FakeInt(10)
while --A:
    print A,

输出:

9 8 7 6 5 4 3 2 1
8

你可以使用ctypes来创建可以改变的整数。不过,选择合适的ctype类型很重要,因为它们会限制整数的大小。

>>> from ctypes import c_int64
>>> num = c_int64(0)
>>> id(num)
4447709232
>>> def increment(number):
...     number.value += 1
... 
>>> increment(num)
>>> increment(num)
>>> increment(num)
>>> num.value
3
>>> id(num)
4447709232
>>> 

更多信息请查看:https://docs.python.org/2/library/ctypes.html#fundamental-data-types

15

整数是不可改变的,也就是说一旦你创建了一个整数,它的值就不能被修改。如果你想要一个可以改变值的整数,就需要自己创建一个类,并把所有整数的方法都写进去。

撰写回答