我今天遇到了类似的问题,并提出了一个名为 IterInt 的类,它允许您使用“+”和“-”装饰器就地递增或递减。
用法:
x = IterInt()
print x
# result: 0
print +x
# result: 1
print +x
# result: 2
print +x
# result: 3
print -x
# result: 2
print -x
# result: 1
print -x
# result: 0
在我的情况下,我想通过在特定索引之后插入几个命令项来修改应用程序的现有菜单。我正在使用的提供的 API 有一个“addCommand”函数,它可以获取要插入的索引。
考虑这个伪代码,其中 menu 有命令 a 到 g,类似于 menu = [a, f, g],我想在索引 1-4 处插入
idx = 1
menu.addCommand(b, index=idx)
idx += 1
menu.addCommand(c, index=idx)
idx += 1
menu.addCommand(d, index=idx)
idx += 1
menu.addCommand(e, index=idx)
idx += 1
# result: menu = [a, b, c, d, e, f]
如果我可以编写它以便 idx 像 c 一样在我可以做 idx++ 的地方增加,那就太好了,但是函数不允许在参数中使用 python 的 idx+=1 方法。
解决方案:
class IterInt(int):
"""
This function will return the next integer from the init_value starting point or 0 if None.
Each subsequent call to increment returns the next value
:param init_value:
:return:
"""
def __init__(self, init_value=None):
if init_value is None:
init_value = 0
if init_value is not None:
self.increment_value = init_value
self.increment_value = init_value
def __pos__(self):
self.increment_value += 1
return self.increment_value
def __neg__(self):
self.increment_value -= 1
return self.increment_value
idx = IterInt(1)
menu.addCommand(b, index=+idx)
menu.addCommand(c, index=+idx)
menu.addCommand(d, index=+idx)
menu.addCommand(e, index=+idx)
# result: menu = [a, b, c, d, e, f]