If you're not committed to classes, you could use a function and abuse using mutable-types-as-default-initializers:
def counter(init=None, container=[0]):
container[0] -= 1
if init is not None: container[0] = init
return container[0]
x = counter(100)
print(x) # 100
print( counter() ) # 99
print( counter() ) # 98
print( counter() ) # 97
# ...
Call counter
with a single argument to set/initialize the counter. Since initialization is actually the first call to the function, it will return that number.
Call counter
with no arguments to get the "next value".
(Very similar to what I suggested here)
Alternatively, for a syntax closer to what you had in your question, use properties:
class Counter(object):
def __init__(self, init):
self.val = init
@property
def value(self):
val = self.val
self.val -= 1
return val
count = Counter(50)
print(count.value) # 50
print(count.value) # 49
print(count.value) # 48
print(count.value) # 47
#...
Here, you're creating a Counter
object called count
, then every time you call count.value
it returns the current value and prepares itself for a future call by decrementing it's internal val
attribute.
Again, the first time you request the value
attribute, it returns the number you initialized it with.
If, for some reason, you want to "peek" at what the next call to count.value
will be, without decrementing it, you can look at count.val
instead.