Should I be using "global" or "self." for class scope variables in Python?

18,642

Solution 1

You should use the second way, then every instance has a separate x

If you use a global variable then you may find you get surprising results when you have more than one instance of Stuff as changing the value of one will affect all the others.

It's normal to have explicit self's all over your Python code. If you try tricks to avoid that you will be making your code difficult to read for other Python programmers (and potentially introducing extra bugs)

Solution 2

There are 2 ways for "class scope variables". One is to use self, this is called instance variable, each instance of a class has its own copy of instance variables; another one is to define variables in the class definition, this could be achieved by:

class Stuff:
  globx = 0
  def __init__(self, x = 0):
    Stuff.globx = x 
  ...

This is called class attribute, which could be accessed directly by Stuff.globx, and owned by the class, not the instances of the class, just like the static variables in Java.

you should never use global statement for a "class scope variable", because it is not. A variable declared as global is in the global scope, e.g. the namespace of the module in which the class is defined.

namespace and related concept is introduced in the Python tutorial here.

Share:
18,642
Greg
Author by

Greg

Updated on June 24, 2022

Comments

  • Greg
    Greg almost 2 years

    Both of these blocks of code work. Is there a "right" way to do this?

    class Stuff:
        def __init__(self, x = 0):
            global globx
            globx = x
        def inc(self):
            return globx + 1
    
    myStuff = Stuff(3)
    print myStuff.inc()
    

    Prints "4"

    class Stuff:
        def __init__(self, x = 0):
            self.x = x
        def inc(self):
            return self.x + 1
    
    myStuff = Stuff(3)
    print myStuff.inc()
    

    Also prints "4"

    I'm a noob, and I'm working with a lot of variables in a class. Started wondering why I was putting "self." in front of everything in sight.

    Thanks for your help!

  • Greg
    Greg about 13 years
    Ah.... the lightbulb goes on! Thank you! After adding "thisStuff = Stuff(5)" before the print statement in each example, example 1 gives "6" and example 2 still gives "4". Thanks again!
  • eyquem
    eyquem about 13 years
    +1 for "global scope = the namespace of the module in which the class is defined." Many people believe that a global is the immidiately outer space of a function or a class , even for a nested one
  • Auspex
    Auspex about 13 years
    Oops. In your __init__(), globx is a global, not an instance variable...[Stuff(1).globx == 0]