Menu
Coddy logo textTech

External Files

Part of the Object Oriented Programming section of Coddy's Python journey — lesson 1 of 64.

External files let you organize your classes in separate Python files and import them into your main program.

Create a separate Python file called my_class.py

class MyClass:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        return f"Hello, I'm {self.name}"

Import the class into your main file

from my_class import MyClass

Create an instance and use it

obj = MyClass("Alice")
print(obj.greet())

Output:

Hello, I'm Alice

The from my_class import MyClass statement connects the my_class.py file to your program. The first my_class is the filename (without .py), and MyClass is the class name inside that file.

challenge icon

Challenge

Medium

You are given Python files (my_class.py and driver.py), add an import statement in the driver.py file to import the MyClass class by name from my_class.py using the syntax: from my_class import MyClass

Cheat sheet

To import a class from an external Python file, use the from statement:

from filename import ClassName

Example with my_class.py containing a class:

# my_class.py
class MyClass:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        return f"Hello, I'm {self.name}"

Import and use the class in your main file:

# main file
from my_class import MyClass

obj = MyClass("Alice")
print(obj.greet())  # Output: Hello, I'm Alice

The filename (without .py) comes after from, and the class name comes after import.

Try it yourself

# TODO: update the import
from ? import ?

# Test code here
test_case = input()
print('Test completed')
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming