Is it possible to have static variable in python?
Hi,
This is not a perfect question from me since I am not much experienced with python.
I have a simple question to ask, is it possible in python to have a static variable or a method just like C++? If yes can anyone please help me with an example here?
Thanks in advance.
Re: Is it possible to have static variable in python?
Well to say particularly for python to have static variable its not there as far as I know.
But you can definitely do the same in various ways for python like for C.
Just use global variable. you can declare bits in set_bit() as "global bits = ..." this will create a global variable & you don't need to declare it outside the function. You have to take care with the name you use while declaration that it wont be confusing.
You can call set_bit(..) as a function.
Re: Is it possible to have static variable in python?
In my opinion one must avoid using global variables since it leads to errors.
You can use a generator function instead.
Code:
def static_num2():
a = 0
while True:
a += 1
yield a
static = static_num2().next
for j in range(0,10) :
print static()