https://docs.python.org/2/library/ctypes.html#fundamental-data-types는 오늘 유사한 문제가 있었다 당신이 "+"를 사용하여 증가 또는 감소 장소에서 할 수 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"함수가 있습니다.
메뉴 메뉴 = [A, F, G] 같은 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 ++를 할 수있는 곳에서 idx를 증가시킬 수 있다면 cx처럼 쓸 수는 있지만 함수는 인수에서 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]
왜 당신이 그것을 위해 접두사 연산자를 구현하고자합니까? ++ n을 메소드 호출로 변환하기 위해 사용자 정의 전 처리기를 추가 할 예정입니까? – Ryan
흠 그냥 파이썬이 할 수있는 친구를 보여주고 싶습니다. --n : print n;) –
익명의 클래스 (변경 가능)에서 int를 래핑하는 약간의 복잡한 방법으로 이것을 보시고 'reference': http://stackoverflow.com/a/1123054/409638 ref = type ('', ('n': 1)) – robert