Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
use of global
#21
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
Reply
#22
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Global variable does not seem to be global. Columbo 6 3,662 Jul-15-2019, 11:00 PM
Last Post: Columbo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020