YHS
YHS

Reputation: 157

python global variable access: keep define in every functions?

I have three functions that want to change a global variable and can't combine into one function, the way I know right now is keep define "global" keyword in each functions to be able to access global variable. Is there a better way to do the same thing with out keep redefining the global variable? for example:

    def fn1(self):
        global NUM
        NUM = 1
        print "fn1 = ",  NUM

    def fn2(self):
        global NUM
        NUM = 2
        print "fn2 = ",  NUM

    def fn3(self):
        global NUM
        NUM = 3
        print "fn3 = ",  NUM

NUM = 0
fn1(NUM)
fn2(NUM)
fn3(NUM)

Thank you

Upvotes: 0

Views: 147

Answers (3)

Pratik Kumar
Pratik Kumar

Reputation: 2231

Why don't you define another function, which changes the value of the global variable with the argument provided as parameter. And call this in rest of your function. For example :

var=None

class A:

  def change(self,num):
     global var
     var = num

  def first(self,num):
    self.change(num)

  def second(self,num):
    self.change(num)

  def third(self,num):
    self.change(num)

a=A()

a.first(1)
print 'value of global variable',var

a.second(2)
print 'value of global variable',var

a.third(3)
print 'value of global variable',var

Otherwise, if the scope of your global variable is supposed to be confined within your class then declare it as a member of the class, and let the functions change it's value. For example :

class A:

  def __init__(self):
     self.var=None
     print "default = ",  self.var

  def first(self,num):
    self.var=num
    print "fn1 = ",  self.var

  def second(self,num):
    self.var=num
    print "fn2 = ",  self.var

  def third(self,num):
    self.var=num
    print "fn3 = ",  self.var




a=A()

a.first(1)
print 'value of variable',a.var

a.second(2)
print 'value of variable',a.var

a.third(3)
print 'value of variable',a.va

Upvotes: 1

ddor254
ddor254

Reputation: 1628

it seems like the function are part of a class , based on the self keyword , if so they all can access class variable without the need of global keyword, if they are not part of a class you can:

define each function with a given parameter to the function and make that function return a value.

 def func1(param_1):
     #work on param_1 
     return param_1

Upvotes: 0

syntonym
syntonym

Reputation: 7384

You can make the global variable a mutable class and then mutate in place.

global_dict = {"data": 1}
global_list = [1]

class MutableInt:
    def __init__(self, value=1):
        self.value = value

global_int = MutableInt()

This works, but personally I wouldn't call that any better. With the global it is at least 100% clear that you change a global variable. Best would be to change your architecture to not need any global variables.

Upvotes: 0

Related Questions