If you want to avoid global
, one possible approach is to define a class. Each class instance has its own attributes; there is also a class attribute space where instances can share an attribute between them.
Object-oriented programming can be challenging to get into if you are new to Python, but this might actually be a good time to start playing with it.
class Thing:
shared = "foo"
def __init__(self):
"""
This gets called when you create a new Thing()
"""
self.bar = "baz" # default value for new instances
def get_bar(self):
return self.bar
def set_bar(self, value):
self.bar = value
Now, let's create two instances.
first = Thing()
second = Thing()
The get_bar
and set_bar
methods are not strictly necessary in simple examples like this one. You can also do
second.bar = "ick"
print(second.bar)
# "ick"
print(first.bar)
# "baz"
(though for more complex scenarios, you probably want to require users to call the setter and getter methods; there are ways to force this - see e.g. What's the pythonic way to use getters and setters?)
If you change a class attribute via one instance, it will not be changed in the other instances, either.
second.shared = "poo"
print(first.shared)
# "foo"
But if you change it in the class itself, it will be changed in all the instances which have not separately overridden the shared value.
Thing.shared = "zoom"
print(first.shared)
# "zoom"
print(second.shared)
# "poo", still
To recap, you create a new Thing
instance by calling Thing()
; this will run the __init__
method before returning the new instance. Inside the class, the instance is the first argument to every (non-static, non-class) method, and conventionally called self
(though you could get away with calling it shirley
if you wanted to, as far as the Python interpreter is concerned).
There's a lot more to classes; the main selling point is probably that you can create subclasses which inherit from their parent class but can override some behaviors (common examples often involve real-world concepts like animals or vehicles, but a class can just be anything where you want to create a type and encapsulate its behavior, and perhaps override some methods in derived types).