I defined a function in that there is a variable num assigned 1000 and increment variable for incrementing the num by one. When it is called for the first time it increments by one and shows the value 1001 but when it is called again it shows the same value 1001 but it should show 1002, 1003 on every call
def number():
num = 1000
increment = num +1
return increment
print(number())
Python allows to attach attributes to a function (after all it is an object of class function).
So you can avoid a global (or non local) variable this way:
def number():
if hasattr(number, "num"):
number.num += 1 # increment if not first call
else:
number.num = 1000 # initialize on first call
return number.num
Demo:
>>> for i in range(10):
print(number())
displays as expected:
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
And there is no risk of clash with another use of a global variable...
But beware. After one night, I realized that while it is what you asked for, this is an anti pattern. This is a stateful function in an OOP language, yerk...
State is supposed to be holded in objects, and functions are supposed to be stateless. You can break this rule, but it could confuse future readers of that code (even you...). So please don't.
Along with the excellent answers already posted, you can also do this using a closure:
def incrementor():
info = {"count": 999}
def number():
info["count"] += 1
return info["count"]
return number
number = incrementor()
>>> number()
1000
>>> number()
1001
>>> number()
1002
(The dict is a bit clumsy, but you can't do it with a simple variable name, at least without using Python 3's nonlocal keyword, which to me feels even more clumsy. This particular example I guess wouldn't be considered very Pythonic - but it's an option, and you will see genuine uses for similar patterns in other Python code.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With