I'm newbie in python.
Is there analogue of static
keyword in python? I needed to implement a simple function allocating an integer ID from the pool, in fact it just increments a global variable and returns it:
id = -1
def generate_id():
global id
id += 1
return id
Is this the right way to do it? In C
I could declare a static
variable in the function.
-
1Does this answer your question? What is the Python equivalent of static variables inside a function?FObersteiner– FObersteiner2019年12月02日 15:15:30 +00:00Commented Dec 2, 2019 at 15:15
-
@MrFuppes, thanks, I will read that thread.Mark– Mark2019年12月02日 15:47:56 +00:00Commented Dec 2, 2019 at 15:47
2 Answers 2
The simple way would be to return a "generator" function that forms a closure over a local, then just manipulate the local:
def new_id_generator():
id = 0
def gen():
nonlocal id
id += 1
return id
return gen
g = new_id_generator()
print(g(), g()) # 1 2
2 Comments
id
variable is only visible inside of new_id_generator()
? So in other words, any other code in the script won't be able to touch/change id
?In python there is no such thing as "static" keyword unlike java.
For Funtions
You can add attributes to a function, and use it as a static variable.
def incrfunc():
incrfunc.tab += 1
print incrfunc.tab
# initialize
incrfunc.tab = 0
For Class
However, if you are making use of the classes in python below is the language convention.
All variables which are assigned a value in class declaration are class variables. And variables which are assigned values inside class methods are instance variables.
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self,name,roll):
self.name = name # Instance Variable
self.roll = roll # Instance Variable
NOTE: If you ask me, it would always be good to make use of classes and use them inside off a class, it is my opinion.