In this tutorial, we will learn how to import a class in Python. Importing a class means including the functionality of one class into another class, which allows you to reuse existing code and make your program more modular and organized. By the end of this tutorial, you will be able to efficiently import and use classes in your Python projects.
Step 1: Create the Class That You Want to Import
Before you can import a class, you need to have a class to import. For the purpose of this tutorial, let us create a simple class called Person with a few attributes and methods. Save this class in a file called person.py.
1 2 3 4 5 6 7 8 9 10 |
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person(name={self.name}, age={self.age})" def greet(self): print(f"Hello! My name is {self.name} and I am {self.age} years old.") |
Step 2: Import the Class into Another File
Now that we have a class to import, let’s create a new Python file called main.py. In this file, you will import the Person class using the import
keyword, followed by the file name without the extension (in this case, person).
1 2 3 4 |
from person import Person john = Person("John Doe", 25) john.greet() |
To import the class, we use the from <module> import <class>
statement, where module. In our case, the module is the file person.py and the class is the Person class.
Step 3: Instantiate and Use the Imported Class
After importing the class, you can now create instances of the Person class and use its methods.
1 2 |
carla = Person("Carla Smith", 35) carla.greet() |
Full Code
For reference, here is the full code for both files.
person.py
1 2 3 4 5 6 7 8 9 10 |
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person(name={self.name}, age={self.age})" def greet(self): print(f"Hello! My name is {self.name} and I am {self.age} years old.") |
main.py
1 2 3 4 5 6 7 |
from person import Person john = Person("John Doe", 25) john.greet() carla = Person("Carla Smith", 35) carla.greet() |
Output
Hello! My name is John Doe and I am 25 years old. Hello! My name is Carla Smith and I am 35 years old.
Conclusion
This tutorial demonstrated how you can import and utilize classes in Python, making it easy to reuse and organize your code. By importing classes, you can build more complex applications while maintaining clean and maintainable code. Happy coding!