increment int object(递增 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 是不可变的,所以如果你想要一个可变的 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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:递增 int 对象
基础教程推荐
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
