Python Practice › OOP Programs › Program 20

Class in a module, imported elsewhere

EasyOOP Programs · 20 of 48

Write a Python class in its own module and import it from another script.

Advertisement
Output
25

Approach

  1. Save the class in shapes.py, then from shapes import Square.

Solution

Python
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.

More oop programs

← All 48 OOP Programs

Leave a Comment