增加int对象

Anu*_*yal 14 python int

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

>>> n=1
>>> id(n)
9788024
>>> n+=1
>>> id(n)
9788012
Run Code Online (Sandbox Code Playgroud)

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

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

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

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
Run Code Online (Sandbox Code Playgroud)

Ark*_*ady 12

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

  • 该类中的int仍然是不可变的. (5认同)
  • 如果类的整数是不可变的,属性的值是可变的,那没有什么区别,所以你可以定义一个工作的“MutableInt”类,而不是你想要的。 (2认同)

Mar*_*kus 5

如果您绝对必须要使该代码正常工作,这是一个肮脏的方法,在该方法中,实例方法在框架上移动并覆盖其自己的本地项。不推荐。(例如,真的不是。我什至不知道那是什么。旧实例发生了什么?我对框架还不了解...)。真的,我之所以这样发布是因为所有人都说这是不可能的,而实际上这只是一种可笑的糟糕形式。;-)

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,
Run Code Online (Sandbox Code Playgroud)

输出:

9 8 7 6 5 4 3 2 1
Run Code Online (Sandbox Code Playgroud)

  • +1有趣,但是是的,我不敢使用 (2认同)

Car*_*ith 5

您可以将不可变对象放入可变容器中;列表是最简单的。

此代码打印0,演示了问题:

a = 0       # `a` points to a new int (a `0`)
b = a       # `b` points to the same thing as `a` (the `0`)
b = 1       # `b` points to a new int (a `1`)
print(a)    # `a` still points to the same thing (the `0`)
Run Code Online (Sandbox Code Playgroud)

如果将 int 放入列表中,但使用与以前相同的代码,则可以获得具有可变 int 的效果(尽管实际上正在改变的是列表):

a = [0]        # `a` points to a new `0` inside a new list
b = a          # `b` points to the same thing as `a` (the list)
b[0] = 1       # the list that `a` and `b` point to is mutated
print(a[0])    # `a[0]` points to the same object as `b[0]` (the `1`)
Run Code Online (Sandbox Code Playgroud)

在实践中,您应该构建数据,以便上述“技巧”是多余的。这些示例不应直接使用,但应帮助您弄清楚该怎么做。


Rob*_*l86 5

您可以将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
>>> 
Run Code Online (Sandbox Code Playgroud)

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