Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 7 · Structuring Code in OOP

Structuring Code in OOP

A Python module is a .py file. Group code by responsibility so changing presentation does not require changing enrollment rules.

Here an artifact is a file, such as model.py. The tabbed package box groups related files in the diagram; it does not create those files or automatically make the folder an importable Python package. A dashed dependency arrow points from the file doing the import toward the file it uses. Follow those arrows to identify which definitions must be available when a module loads.

Project filesmodels.pycontroller.pyviews.pymain.pyimportsimportsimports

Start in one file, then separate:

  • models.py: Student, Course, Enrollment and their rules.
  • controller.py: coordinate a request and handle expected model errors.
  • views.py: format the result.
  • main.py: create objects and run the application.

For this simple layout, put the files in one project folder. from models import Student imports the class into another module. Keep the model independent of the view to avoid circular dependencies.

Apply it: identify which file should reject duplicate enrollment, and which should change the wording of its message.

A component diagram makes these software parts and their dependencies visible in one view.