0

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.

asked Dec 2, 2019 at 15:00
2

2 Answers 2

1

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
answered Dec 2, 2019 at 15:16

2 Comments

thanks for feedback. In new_id_generator() function -- is it guaranteed that 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 ?
@Mark There's potentially some bizarre hack by inspecting stack frames that will allow it to be changed, but it will be much harder than it would by having it as a attribute of a function or your own class. Python doesn't have strict "private" controls, so you can really only discourage certain behavior, not outright prevent it. I think this is about as "private" as you'll be able to get.
1

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.

answered Dec 2, 2019 at 15:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.