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 MyClassCreate an instance and use it
obj = MyClass("Alice")
print(obj.greet())Output:
Hello, I'm AliceThe 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
MediumYou 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 ClassNameExample 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 AliceThe 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')This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes