Python Practice › OOP Programs › Program 20
Class in a module, imported elsewhere
Write a Python class in its own module and import it from another script.
Output
25
Approach
- Save the class in
shapes.py, thenfrom shapes import Square.
Solution
with open("shapes.py", "w") as f: f.write("class Square:\n" " def __init__(self, side):\n" " self.side = side\n" " def area(self):\n" " return self.side ** 2\n") from shapes import Square print(Square(5).area())Output
25
Line by line
Lines 1-6
Creates the module file so the example is self-contained; normally you would write shapes.py in your editor.
Line 8
Module-level import makes Square available in this script.
Learn the concept
New to this topic? Read the lesson, then come back.