Its all about scope, since text
is declared outside, free from any class or function, it can be reached from anywhere. To get a better idea, consider these two examples:
#!/usr/bin/env python
text = "why is this seen?"
class Foo:
def doit(self):
text = "this is changed"
print(text)
x = Foo()
x.doit()
print text
In the above example, we overwrite the text
variable locally, in the Foo
, class, but the global instance of text is the same. But in this instance:
#!/usr/bin/env python
text = "why is this seen?"
class Foo:
def doit(self):
global text
text = "this is changed"
print(text)
x = Foo()
x.doit()
print text
We declare that we want the global
version of text and then we can modify it.
BUT: global
variables are frowned upon, consider using input arguments to functions and returning new values instead of having variable globally accessible everywhere
The right way to do it:
#!/usr/bin/env python
class Foo:
text = "why is this seen?"
def doit(self):
print(self.text)
x = Foo()
x.doit()
Have text
encapsulated in the class!