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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With