Python Forum

Full Version: use of global
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
I too struggler with using classes and I too don't like to use global statements.
To get around this I use a very simple class (that even I can understand)
to hold all the variables and thus making the variables global without using
the global statement.
Note: This way will be very much frowned upon by Python developers, but
I find it a useful stop-gap until IU can properly get my head around classes.

Example:
class Glo:
    '''global store, this makes these vars global,e.g Glo.var'''
    save_on = True
    stop_thread = False
    file_name = ""
    file_inc = 0
    image_count = 0
    grab_secs = 2
    max_images = 7200
Then I can use the variables like this:
Glo.max_images +=1
if Glo.grab_secs etc....

For a full explanation:
https://stevepython.wordpress.com/2019/0...-variables
what you do is not removing global variables, but just masking their use by turning them in class attributes and working with the class, not instance of it.
you can do it also with dict or other mutable objects
# DON'T DO THIS
foo = {"save_on": True, "stop_thread": False, "image_count":0}

def bar():
    foo["image_count"] += 1

bar()
print(foo)
in both cases you don't solve the inherent problems
Pages: 1 2 3