Python| How can I make this variable global without initializing it as 'global'
I have this code here. The only part I can add code to is in main_____ AFTER the 'i=1' line. This script will be executing multiple times and will have some variable (might not be 'i', could be 'xy', 'var', anything), incrementing by 1 each time. I have gotten this to work by declari开发者_运维知识库ng 'i' as global above the method, but unfortunately, I can't keep it that way.
Is there a way in which I can make 'i' function as a global variable within the above-mentioned parameters?
def main______():
try:
i+=1
except NameError:
i=1
main______()
If you want to use a global variable you have to declare it as global. What's wrong with that?
If you need to store state between calls, you should be using a class
>>> class F():
... def __init__(self):
... self.i=0
... def __call__(self):
... print self.i
... self.i+=1
...
>>> f=F()
>>> f()
0
>>> f()
1
>>> f()
2
精彩评论