I'm new to programming, and have recently learned python and the basics of object oriented programming. I'm aware that having lots of global variables is generally a bad idea, and that I can put them all into a class instead. Is this the right way to do it?
class GameState(object):
def __init__(self):
self.variable1 = 1
self.variable2 = 2
self.list = [3, 4, 5]
g_state = GameState()
And, if I wish to access the variables within g_state, what is the best way to go about doing it?
Pass g_state into the functions/classes that need access? Implement getters and call those? Use g_state.variable1 directly?
Or is there a better way?
EDIT: To be more specific, I'm trying to write a game in python using pygame, and was thinking of putting my gamestate variables into a class so as to not have a bunch of global variables lying around. I'm unsure of how to access those variables with good design so I don't run into trouble later.
You are right that too many global variables is not a good idea. Polluted global namespace may lead to errors.
However, don't put them into class for the sake of it. If you have really that many variables maybe you should consider splitting your program into multiple modules.
Also please understand that you can't really crate global variables in Python like you can in JavaScript. Your variables are always scoped under the module.
Let me illustrate with an example. Module a.py:
A = 42
Module b.py:
import a
print(A)
What do you get? NameError. Why? because variable A is not global, it is under module a. You need to use a.A to reference it.
There is no need to stuff variables under class. They are under modules, which acts as a namespace, and there is nothing wrong with it.
Creating a class simply for storing variables is not necessary. A class would only be needed if you really do need multiple instances of that class, each with unique values.
But for a single global state, a dictionary object can suffice for this purpose. You can store it in a module specifically intended for config and state if you want:
conf.py
GAME_STATE = {
'level': 0,
'score': 0,
'misc': [1,2,3],
}
main.py
import conf
conf.GAME_STATE['score'] = 100
So your other modules can just import the conf.py module and access the state dict. You can store whatever types you need in this object. It also gives you a convenient location to add functionality for serializing these values out to disk if you want, and reading them back at future runs of the program, and to keep them alongside configuration options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With