Here is an answer to expand on my comment regarding setting a
as a class attribute, rather than using a global
.
The Short Answer:
- Use
global
s with controlled caution; or the safe play ... just don't. There's usually a better way.
- Passing variables is OK
- Use a
class
at any (applicable) opportunity
Class Example:
Here is a simple, stripped down class structure with no frills. You'll notice the absence of any global variables, along with no passed variables.
This is not saying that passed variables are discouraged, they are useful, if not necessary. However, this is to show that globals are not needed, and there's usually a better way. For what it's worth ... (personally speaking, I've never seen the use for them in Python).
class Demo():
"""Class attribute demonstration class."""
def __init__(self):
"""Demo class initialiser."""
self._a = 73
def add_one(self):
"""Add one to the `a` attribute."""
self._a += 1
def times_two(self):
"""Multiply the `a` attribute by two."""
self._a *= 2
Use Case:
I'll be the first to point out that this example is all but useless in the real world due to 1) externally accessing a 'private' class attribute and 2) the continued updating of _a
; this is only an example specific to your question.
Note that each call to a different function has a different, yet continued affect on _a
; noting the variable (class attribute) is neither global, nor passed.
demo = Demo()
print(f'Value of _a: {demo._a}')
>>> Value of _a: 73
demo.add_one()
print(f'Value of _a plus one: {demo._a}')
>>> Value of _a plus one: 74
demo.times_two()
print(f'Value of _a plus one, times two: {demo._a}')
>>> Value of _a plus one, times two: 148