public variable python code example
Example 1: python static variable in function
"""1/You can add attributes to a function, and use it as a
static variable."""
def foo():
foo.counter += 1
print ("Counter is %d" % foo.counter)
foo.counter = 0
"""2/If you want the counter initialization code at the top
instead of the bottom, you can create a decorator:"""
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
@static_vars(counter=0)
def foo():
foo.counter += 1
print ("Counter is %d" % foo.counter)
"""3/Alternatively, if you don't want to setup the variable
outside the function, you can use hasattr() to avoid an
AttributeError exception:"""
def myfunc():
if not hasattr(myfunc, "counter"):
myfunc.counter = 0
myfunc.counter += 1
Example 2: global variable not working python
trying to assign a global variable in a function will result in the function creating a new variable
with that name even if theres a global one. ensure to declare a as global in the function before any
assignment.
a = 7
def setA(value):
global a
a = value
Example 3: python global variables
global var1
var1 = 'whatever'
Example 4: python access global variable
globvar = 0
def set_globvar_to_one():
global globvar
globvar = 1
def print_globvar():
print(globvar)
set_globvar_to_one()
print_globvar()
Example 5: global variable python
a = 0
def testFor():
global a
if(a == 0):
Example 6: python local variables
'''Local variables are those that are defined in a block '''
a = 1
def add():
b = 1
print(b)
add()