Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 670
Greg Avatar asked Mar 07 '11 23:03

Greg


People also ask

Should you avoid using global variables in Python?

While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.

Do class variables need self?

The value of the instance variable will be unique to the instance objects of the class that might be declared. However, if you want the variables to be shared by all instances of the class, you need to declare the instance variables without self.

Is it better to use mostly global or mostly local variables in your code?

Always prefer local over global. If you need to pass the data in as multiple parameters, so be it. At least then you're explicitly saying what data your function depends on. Having too many parameters is certainly a problem, but offloading some of them as globals isn't the answer.

Can global variables be used in classes?

A global variable is a visible variable and can be used in every part of a program. Global variables are also not defined within any function or method. On the other hand, local variables are defined within functions and can only be used within those function(s).


1 Answers

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)

like image 167
John La Rooy Avatar answered Sep 20 '22 03:09

John La Rooy