Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Organize Classes in Python?

I've come across an issue that I feel has an extremely simple answer but is hard to explain in a short Google search and I can't find anything about this topic.

So, in a recent game I've been working on I have multiple types of objects for every block/tile in the game:

    class Char(object):
        ...
        def update(self):
            ...
        def move(self, direction):
            ...

or

    class Dirt(object):
        ...

and obviously, defining all of these classes in the main program can be very messy, for example, what if I wanted to create an object in the game that had the name "screen" (a computer screen), well this would conflict with my screen class for the actual game window. And, further more, creating a second module called gameObjects also causes the problem that all my game objects don't have access to variables defined in main.

So, how can I organize, or group, my classes? I'm a beginner getting into Python, so a simple answer would be appreciated, thanks.

like image 487
Parker Hoyes Avatar asked Mar 02 '26 17:03

Parker Hoyes


1 Answers

You generally don't want to have objects that have the same names as your classes. If they're not defined at the same scope, there isn't actually a conflict, but it's still confusing.

However, if you follow the typical Python naming conventions, this won't be a problem: your classes start with capital letters, and your variables start with lowercase letters. So, your variable is called screen, and it doesn't matter that you have a class called Screen.

Meanwhile, you do probably want to put related classes together into a module. Objects of classes defined in your gameObjects module will not have access to variables defined in main, but you don't want them to. Global variables are almost always a bad idea. If an object needs access to a variable, pass that variable into its constructor.

Before creating your own large project, you should probably look around a few other large projects to see how they organize things.

like image 139
abarnert Avatar answered Mar 05 '26 07:03

abarnert