Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What is the difference between a global variable, vs. a variable with the prefix "self.", vs. a local variable?

I've been exposed to C/C++/Java like syntax over the years, and the way that Python variables are defined just sort of confuses me. Can anyone describe what the differences are among the three mentioned in the q?

like image 756
Chuck Testa Avatar asked Dec 02 '25 08:12

Chuck Testa


1 Answers

A global variable is just that -- a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition. An instance variable (e.g.: when using the self. prefix) is data that is associated with a specific instance of an object. Of course, you can also reference instance objects outside of the object by using object.x where object is a reference to that object.

If a variable is prefixed with self, it is neither local nor global. It is part of the makeup of a specific instance of an object. Roughly speaking, an instance variable represents a property of a specific object.

In the following example, lx is a local variable, local to the method greet. gx is a global variable accessible anywhere in the module, ix is an instance variable that could have a unique value for each instance of the object. When referenced inside of the object definition you would refer to ix with the prefix self, and when outside the object with a prefix of the object reference.

gx = "hello"
class Foo:
    def __init__(self, who):
        self.ix = who
    def greet(self):
        lx = "%s, %s" % (gx, self.ix)
        return lx

foo = Foo("world")
print foo.greet()
print foo.ix
like image 69
Bryan Oakley Avatar answered Dec 06 '25 11:12

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!