How to organize my Python code into several classes?

I was recently told that I should store my code in separate files; for example main.py, engine.py, settings.pyand so on. Although it certainly has advantages such as simple management, scalability, and others, it seems to me that it has too many disadvantages ...

For example, if I have a script called settings.pywhere certain things are defined, such as sizes of display objects, modeling speed and color of various objects, what should I do if these variables are needed both in my engine.pyscript and my main.pyscript? Do I import it twice in both scenarios? It seems pretty dirty. What if some of my classes that are in the engine.pyscript require code from main.py?

Let me show you the exact situation ...

My main.pyscript imports Pygame on its own, initializes it, etc. It used to have a class that was a display object, and this class had a method drawthat was simply called the Pygame drawing function. Now when I put the class in my engine.pyscript, everything no longer works, because Pygame does not exist there! I ended up importing both settings.pyPygame and both engine.py, and then importing the slider into main.py, but then it looks more like an initializer than a slider ... Is there a way to deal with things like shared guidelines?

+5
source share
6 answers

Here are the official PEP guidelines for importing: http://www.python.org/dev/peps/pep-0008/#imports

. StackOverflow: Python?

, , . Python

+3

, :

settings.py settings.ini, , ConfigParser. ConfigParser.RawConfigParser .

+1

( Java, ) .

, .

, .

Python ?

+1

. , .

, . . , ", engine.py script, , Pygame ! settings.py, Pygame engine.py main.py".

engine.py, main.py? - :

# engine.py
...
class ClassWithDraw(Subclass):
    def __init__(self, draw_callback):
        ...
        self._draw_func = draw_callback
        ...
    def draw(self):
        self._draw_func()

# main.py

from engine import ClassWithDraw
drawer = ClassWithDraw(drawfunc)

, , : . , draw; draw_hook, , , .

, Pygame. Pygame, , , , , Pygame. , main , .

+1

You can import characters from settings.py in any module that they need. This is a concept. The real problem is that you have cyclic imports. for example What if you have symbols inside engine.pythat were needed in main.pyand vice versa. In this situation, the general template is to break these dependencies in the third module, where main.pythey engine.pycan be imported without any problems.

0
source

All Articles