To import a class from another file in Python, use the import statement along with the name of the module.
Alternatively, if you need only a specific class from a module, you can directly import that class.
Let’s assume app1.py contains a class that you want to use in app2.py.
Here’s step-by-step guide:
Step 1: Define a class in app1.py
# app1.py
class MyClass:
def __init__(self):
print("MyClass instance created!")
def sum(self, x, y):
return x + y
def multiply(self, x, y):
return x * y
Step 2: Import the class in app2.py
# app2.py
import app1
my_class_instance = app1.MyClass()
print(my_class_instance.sum(5, 10))
print(my_class_instance.multiply(5, 10))
Step 3: Run app2.py
When you run app2.py, the MyClass from app1.py will be used.
Output
MyClass instance created!
15
50