Python Import Class From Another File [Step by Step guide]

 

Python Import Class From Another File [Step by Step guide]

In this tutorial, we will learn about Python import Class from another file. Classes in any programming language are fundamental to Object Oriented programming and are essential for creating organized, reusable and maintainable code. We will learn about the methods to reuse classes using import functionality in the upcoming sections. So let’s get started.

 

What is Class in Python and why is it needed?

In Python, a class is a blueprint for creating objects. t defines a set of attributes and behaviors that will characterize any object instantiated from this class. Classes allows us to bundle data (in form of attributes) and functionality (in form of methods) together.

Classes are required because it provides a way to organize code into reusable and understandable chunks. It encapsulates data and methods. Hence, allows us to focus on the object’s behavior rather than its internal implementation details. We will learn about Class creation and how Classes are reused in the next section.

 

Python Import Class from Another File [Step by Step guide]

Have you ever come across a requirement where you want to use the functionality of one class into another class?. I believe, you all must have face it and that is pretty common use case in developer’s day to day job. In Python, twe use functionality of one class into other Python files by using the “import” keyword to import the classes. We will learn about three common and most used ways to import the classes from one Python file into another file.

Let us create a Python file and call it generic.py. It defines three classes namely, Vehicle, Animal and Rectangle. Eachi class has it’s own methods and functions defined. Each class also has an __init__ method which will initialize the object of each class respectively. We will call generic.py file generic module in rest of the tutorial. Create below code and save it as generic.py file.

> generic.py

class Vehicle:

    def __init__(self, brand, model, year):

        self.brand = brand
        self.model = model
        self.year = year

    def car(self, color, fuel_type):

        self.color = color
        self.fuel_type = fuel_type
        print(f"Car Details: Brand -> {self.brand}, Model -> {self.model}, Year -> {self.year}, Color -> {self.color}, Fuel Require -> {self.fuel_type}")

    def bike(self, color, engine_capacity):

        self.color = color
        self.engine_capacity = engine_capacity
        print(f"Bike Details: Brand -> {self.brand}, Model -> {self.model}, Year -> {self.year}, Color -> {self.color}, Capacity -> {self.engine_capacity}")

class Animal:

    def __init__(self, color, breed):

        self.color = color
        self.breed = breed

    def dog(self, sound, bite):

        self.sound = sound
        self.bite = bite
        print(f"Dog Detail: Color -> {self.color}, breed -> {self.breed}, Sound -> {self.sound}, Bite -> {self.bite}")

    def cat(self, sound, walk):

        self.sound = sound
        self.walk = walk
        print(f"Cat Detail: Category -> {self.category}, Color -> {self.color}, breed -> {self.breed}, Sound -> {self.sound}, Walk -> {self.bite}")

class Rectangle:

    def __init__(self, len, wid):

        self.len = len
        self.wid = wid

    def perimeter(self):

        per = 2*(self.len + self.wid)
        print(f"Perimeter of rectangle is: {per}")

 

Import single class from a File

The first method to import a class from generic module is by using the from and import keyword. We use ‘from’ keyword to mention the module name in which the class is present. Then we use ‘import’ keyword to only import one specific class (Vehicle in this case) as shown in below code.

After, we have imported the class Vehicle, we will instantiate the classes by creating its objects  as shown below. When we execute this code, it will print the message defined in Vehicle class. Create and save below code as app.py.

> app.py

from generic import Vehicle

v1 = Vehicle("Tata", "Nexon", 2022 )
v1.car("Black", "Petrol")

v2 = Vehicle("Honda", "CBR1000RR", 2021 )
v2.bike("Red", 1000)

OUTPUT

Car Details: Brand -> Tata, Model -> Nexon, Year -> 2022, Color -> Black, Fuel Require -> Petrol
Bike Details: Brand -> Honda, Model -> CBR1000RR, Year -> 2021, Color -> Red, Capacity -> 1000

 

Import multiple classes from a File

We have seen how we can import one specific class from a module. What if we want to import more than one class? Is it possible? . The answer is yes, we can import more than one class from a module in a Python file using comma(,) in import statement. Notice in below code that we are import two classes from generic module. They are Vehicle and Animal. We then have instantiated both the class. When you execute below code, message from both the classes will be printed. Modify the app.py file with below code.

from generic import Vehicle, Animal

v1 = Vehicle("Tata", "Punch", 2022 )
v1.car("Grey", "Petrol")

a1 = Animal("White", "Chihuahua")
a1.dog("BhowBhow", "Yes")

OUTPUT

Car Details: Brand -> Tata, Model -> Punch, Year -> 2022, Color -> Grey, Fuel Require -> Petrol
Dog Detail: Color -> White, breed -> Chihuahua, Sound -> BhowBhow, Bite -> Yes

 

Import All classes from a File

In our example, generic module consists of only three classes. But what if there is a module (like os, sys modules) which has large number of classes defined and we do not exactly know which all class we require during development. In such case you can import all the classes from a module that mean you will import the complete module. This will give access to all the classes define in that specific Module. We import a module using ‘*’ in the from statement as shown below. Modify the app.py file with below code.

from generic import *

v1 = Vehicle("Tata", "Punch", 2022 )
v1.car("Grey", "Petrol")

a1 = Animal("White", "Chihuaha")
a1.dog("BhowBhow", "Yes")

r1 = Rectangle(2, 3)
r1.perimeter()

OUTPUT

Car Details: Brand -> Tata, Model -> Punch, Year -> 2022, Color -> Grey, Fuel Require -> Petrol
Dog Detail: Color -> White, breed -> Chihuaha, Sound -> BhowBhow, Bite -> Yes
Perimeter of rectangle is: 10

 

 

Bonus

There are two ways to import modules in a Python file. These are:

  • from module1 import class1
  • import module

The way we call classes from each import method differs. In all above examples you saw how using from keyword, classes are import. If you want to import module using second method, then you can rewrite the app.py as shown below.

import generic

v1 = generic.Vehicle("Tata", "Punch", 2022 )
v1.car("Grey", "Petrol")

a1 = generic.Animal("White", "Chihuaha")
a1.dog("BhowBhow", "Yes")

r1 = generic.Rectangle(2, 3)
r1.perimeter()

OUTPUT

Car Details: Brand -> Tata, Model -> Punch, Year -> 2022, Color -> Grey, Fuel Require -> Petrol
Dog Detail: Color -> White, breed -> Chihuaha, Sound -> BhowBhow, Bite -> Yes
Perimeter of rectangle is: 10

 

Summary

We learnt about importing one or more classes from a single module. We can also import multiple classes from motre than one module. All we have to do is to import the correct module from where you want to use the class. You can try this exercise by yourself.

 

Leave a Comment