Browse by Domains

Classes and Objects in Python

Table of contents

What do you see when you look around you? You see a lot of objects, don’t you!

If you see a laptop in front of you, what is it? Well, it is a real-world object!

Similarly, if there’s a car on the road? What is that? A car again is a real-world object!

Now, if you see a dog on the street, what do you think it is? You guessed It right, it’s an object again!

Now, if you have to represent these real-world entities in the programming world, you would need an object-oriented programming language. This is where Python comes to the rescue! Python is the most widely used object-oriented programming language and it is also pretty simple to learn.

So, let’s understand Object-Oriented Programming in python  –

Object-Oriented Programming in Python comprises of two main components:

  • Classes
  • Objects(This is obvious 🙂 )

Let’s start with Classes ~

You can consider a class to be a template/blueprint for real-world entities. Let’s take this example to understand the concept of classes better:

If we take a class called as ‘Phone’. You can consider this to be a template for the real-world entity phone.

This class would have two things associated with it: Properties and Behaviour.

The class ‘Phone’ would have certain properties associated with such as:

  • Color
  • Cost &
  • Battery Life

Similarly, the class ‘Phone’ would have certain behavior associated with such as:

  • You can make a call
  • You can watch videos &
  • You can play games

When you combine these properties and behavior together, what you get is a class!

Now, let’s learn about objects!

Simply put, you can consider objects to be specific instances of a class.

So, if ‘Phone’ is our class, then ‘Apple’, ‘Motorola’ and ‘Samsung’ would be the specific instances of the class, or in other words, these would be the objects of the class ‘Phone’.

Now that this covers the basics of object-oriented programming, you’d want to deep dive into OOP with Python.


Let’s go ahead and create our first class in python:

class Phone:

    def make_call(self):

        print(“Making phone call”)

    def play_game(self):

        print(“Playing Game”)

Code Explanation:

Here, we have created a new class called ‘Phone’. To create a new class we use the keyword ‘Class’ and follow it up with the class-name. By convention, the class-name should start with a capital letter.

Inside the class, we are creating two user-defined functions:

make_call() and play_game().

make_call() method is just printing out “making a phone call” and play_game() method is just printing out ‘Playing Game’.

Machine learning is simplifying sales forecasting.


Now that we have created the class, we’d have to go ahead and create an object of the class:

p1=Phone()

p1.make_call()

p1.play_game()

Code Explanation:

We are creating a new object called as p1 with the command: p1=Phone(). Now, if we’d have to invoke the methods which are present in the class, we’d have to use the ‘.’ operator.

To invoke the make_call() method from the Phone class, we use: p1.make_call(). Similarly, to invoke the play_game() method from the Phone class, we use: p1.play_game().


Now, let’s go ahead and add parameters to the methods of our class:

class Phone:

    def set_color(self,color):

        self.color=color

    def set_cost(self,cost):

        self.cost=cost

    def show_color(self):

        return self.color

    def show_cost(self):

        return self.cost

    def make_call(self):

        print(“Making phone call”)

    def play_game(self):

        print(“Playing Game”)

Code Explanation:

Inside the Phone class, we are creating 6 methods:

  • set_color()
  • set_cost()
  • show_color()
  • show_cost()
  • make_call()
  • play_game()

set_color(): This method takes in two parameters: self and color. With the code self.color=color, we are able to set a color to the attribute ‘color’.

set_cost(): This method also takes in two parameters: self and cost. With the code: self.cost=cost, we are able to set a cost value to the attribute ‘cost’.

show_color(): With this method, we are just returning the color of the phone.

show_cost(): With this method, we are returning the cost of the phone.

make_call(): With this method, we are simply printing out: “Making a phone call”.

play_game(): With this method, we are printing out: “Playing Game”


Now that we have created the class, it’s time to instantiate the class and invoke the methods:

p2=Phone()

p2.set_color(“blue”)

p2.set_cost(100)

p2.show_color()

p2.show_cost()

Code Explanation:

We start off by instantiating the class Phone: p2=Phone(). Once, we have the object, it’s time to go ahead and invoke the methods of the object.

By using, p2.set_color(“blue”), we are passing in the value “blue” to the attribute color.

Similarly by using, p2.set_cost(100), we are passing in the value 100 to the attribute cost.

Now, that we have assigned the color and cost to the attributes, it’s time to return the values.

By using, p2.show_color(), we go ahead and print out the color of the phone.

Similarly by using, p2.show_cost(), we go ahead and print out the cost of the phone.


Constructor in Class: 

A constructor is a special type of method inside a class, with the help of which we can assign the values to the attributes directly during the instantiating of the object.

Let’s understand the concept of constructor, through this example:

class Employee:

    def __init__(self,name,age, salary,gender):

        self.name = name

        self.age = age

        self.salary =  salary

        self.gender = gender

    def employee_details(self):

        print(“Name of employee is “,self.name)

        print(“Age of employee is “,self.age)

        print(“Salary of employee is “,self.salary)

        print(“Gender of employee is “,self.gender)

Code Explanation:

Here, we are creating a new class called as Employee. Inside the ‘Employee’ class, we have two methods:

  • __init__()
  • employee_details()

__init__() method is what is known  as the constructor in the class. With the help of this __init__ method, we are able to assign the values for name, age, salary and gender.

By using,  self.name = name, we are assigning the value for name. Similarly, by using, self.age = age, we are assigning the value for age. Then by using,    self.salary =  salary, we are assigning the value for salary. And finally, we are assigning the value for gender by using: self.gender = gender.

Then, with the help of the employee_details() method, we are just printing out the values for name, age, salary and gender.


Now, that we have created a class using a constructor, it’s time to create an object and instantiate the values with the help of this object:

e1 = Employee(‘Sam’,32,85000,’Male’)

e1.employee_details()

Code Explanation:

By using this command: e1 = Employee(‘Sam’,32,85000,’Male’), we are creating an object of Employee class e1 and also instantiating the values for name, age, salary and gender.

We pass in the value ‘Sam’ for name, 32 for age, 85000 for salary and ‘male’ for gender.

Then, we just go ahead and print out the employee details by using the command: 

e1.employee_details()


Inheritance:

With inheritance one class can derive the properties of another class.

Consider this example: You would have certain features similar to your father and your father would have certain features similar to your grandfather. This is what is known as inheritance. Or in other words, you can also say that, you have inherited some physical traits from your father and your father has inherited some physical traits from your grandfather.

Now, that we know what exactly is inheritance, let’s see how can implement inheritance in python:

class Vehicle:

    def __init__(self,mileage, cost):

        self.mileage = mileage

        self.cost = cost

    def show_details(self):

        print(“I am a Vehicle”)

        print(“Mileage of Vehicle is “, self.mileage)

        print(“Cost of Vehicle is “, self.cost)

Code Explanation:

Here, we are creating our parent class called as ‘Vehicle’. This class has two methods:

  • __init__()
  • show_details()

With the help of __init__() method, we are just assigning the values for mileage and cost. Then, with the help of ‘show_details()’, we are printing out the mileage of the vehicle and the cost of the vehicle.


Now, that we have created the class, let’s go ahead and create an object  for it:

v1 = Vehicle(500,500)

v1.show_details()

Code Explanation:

We are starting off by creating an instance of the Vehicle class. The Vehicle class takes in two parameters which are basically the values for mileage and cost. Once, we assign the values, we just go ahead and print out the details, by using the method v1.show_details().


Now, let’s go ahead and create the  child class:

class Car(Vehicle):

    def show_car(self):

        print(“I am a car”)

c1 = Car(200,1200)

c1.show_details()

c1.show_car()

Code Explanation:

We are starting off by creating the child class ‘Car’. This child class inherits from the parent class “Vehicle”.

This child class has it’s own method ‘show_Car()’, which just prints out ‘I am car’. Once we create the child class, it’s time to instantiate the class. We use the command: 

c1 = Car(200,1200), to create an object ‘c1’ of the class ‘Car’. 

Now, with the help of c1, we are invoking the method, c1.show_details(). Even though, show_details in exclusively a part of the ‘Car’ class, we are able to invoke it because the ‘Car’ class inherits from the ‘Vehicle’ class and the show_details() method is part of the Vehicle class.

Finally, we are using c1.show_car() to go and print out ‘I am car’.


Now, let’s see how can we over-ride the __init__ method during inheritance:

class Vehicle:

    def __init__(self,mileage, cost):

        self.mileage = mileage

        self.cost = cost

    def show_details(self):

        print(“I am a Vehicle”)

        print(“Mileage of Vehicle is “, self.mileage)

        print(“Cost of Vehicle is “, self.cost)

Code Explanation:

We are again creating the same parent class ‘Vehicle’ with the methods : __init__() and show_details().


Now, let’s go ahead and over-ride the init method inside child class ‘Car’:

class Car(Vehicle):

    def __init__(self,mileage,cost,tyres,hp):

        super().__init__(mileage,cost)

        self.tyres = tyres

        self.hp =hp

    def show_car_details(self):

        print(“I am a car”)

        print(“Number of tyres are “,self.tyres)

        print(“Value of horse power is “,self.hp)

Code Explanation:

Here the child class ‘Car’, itself has an __init__() method. This __init__() method takes in 5 parameters:

  • Self
  • Mileage
  • Cost
  • Tyres
  • Hp

Inside the __init__() method, we are using super() method to pass in parameters for the parent class. So, mileage and cost go into the parent class’s __init__() method.

Once we pass in the parameters of the parent class, we are assigning the values for ‘tyres’ and ‘hp’.

By using   self.tyres = tyres, we are assigning the value for ‘tyres’. Similarly, by using self.hp =hp, we are passing in value for ‘hp’.

Then we have another method called as show_car_details(), with the help of which we are just printing out the number of tyres in the car and the horse power of the car.


Now, let’s go ahead and create an instance of the car class:

c1 = Car(20,12000,4,300)

c1.show_details()

c1.show_car_details()

Code Explanation:

We are starting off by creating an object of the car class. This take in 4 parameters:

  • 40 for the Mileage of the car
  • 12000 for the cost of the car
  • 4 for the number of tyres
  • HP for the value of horsepower of the car

Then, we go ahead and invoke c1.show_details(), which is from the parent class. Similarly, we invoke c1.show_car_details(), which is from the child class.


Multiple Inheritance:

In multiple inheritance, the child inherits from more than one class.

Let’s have an example to understand the concept of multiple inheritance:

class Parent1(): 

    def assign_string_one(self,str1): 

        self.str1 = str1

    def show_string_one(self): 

        return self.str1

class Parent2(): 

    def assign_string_two(self,str2): 

        self.str2 = str2

    def show_string_two(self): 

        return self.str2

class Derived(Parent1, Parent2): 

    def assign_string_three(self,str3): 

        self.str3=str3

    def show_string_three(self): 

        return self.str3

Code Explanation:

We start off by creating our first parent class “Parent1”. This parent class has two methods:

  • assign_string_one()
  • show_string_one()

With the help of assign_string_one(), we are printing out the value of the attribute str1. Then, with the help of show_string_one(), we are just printing out the value of attribute str1.

Once, we have defined our first class, we go ahead and create our second parent class: “Parent2”. This class again has two methods:

  • assign_string_two()
  • show_string_two()

With the help of assign_string_two(), we are printing out the value of the attribute str2. Then, with the help of show_string_two(), we are just printing out the value of attribute str2.

Finally, we go ahead and create our child class: “Derived”. This “Derived” class is inheriting from both “Parent1” and “Parent2”.

This “Derived” class again has two methods:

  • assign_string_three()
  • show_string_three()

With the help of assign_string_three(), we are printing out the value of the attribute str3. Then, with the help of show_string_three(), we are just printing out the value of attribute str3.


Now, that we have all the classes ready, let’s go ahead and create an object for the “Derived” class:

d1 = Derived()

d1.assign_string_one(“one”)

d1.assign_string_two(“two”)

d1.assign_string_three(“three”)

d1.show_string_one()

d1.show_string_two()

d1.show_string_three()

Code Explanation:

We create the object d1 for the class “Derived” by using this command: d1 = Derived(). Then, we go ahead and assign the value for str1 by invoking assign_string_one(). Similarly, we assign the value for str2 by invoking assign_string_two() and finally we assign the value for str3 by invoking assign_string_three().

Once we assign the values, we print out the values for str1, str2 and str3.


In multilevel Inheritance, we have parent-child-grandchild relationship.

Let’s go through an example to understand this better:

class Parent(): 

    def assign_name(self,name): 

        self.name = name

    def show_name(self): 

        return self.name

class Child(Parent): 

    def assign_age(self,age): 

        self.age = age

    def show_age(self): 

        return self.age

class GrandChild(Child): 

    def assign_gender(self,gender): 

        self.gender = gender

    def show_gender(self): 

        return self.name

Code Explanation:

We start off by our first class “Parent”. This class has two methods:

  • assign_name()
  • show_name()

With the help of assign_name(), we are assigning the value for name attribute. Then, with the help of show_name(), we are returning the value for name.

Once we have created the “Parent” Class, we are creating the “Child” class. This “Child” class is inheriting from the “Parent” class.

This class again has two methods:

  • assign_age()
  • show_age()

With the help of assign_age(), we are assigning a value for the age attribute. Then, with the help of show_age(), we are printing out the value for age.

Finally, we have the “GrandChild” class. This class is inheriting from the “Child” class.

Inside this class we have two methods:

  • assign_gender()
  • show_gender()

With the help of assign_gender(), we are assigning a value for the “gender”. With the help of show_gender(), we are returning the value for gender.


Now that we have created the classes, let’s go ahead create an object for the GrandChild class:

g1 = GrandChild()

g1.assign_name(“Sam”)

g1.assign_age(25)

g1.assign_gender(“Male”)

g1.show_name()

g1.show_age()

g1.show_gender()

Code Explanation:

Here, we are creating the object ‘g1’ for the ‘GrandChild’ class by using this command: 

g1 = GrandChild().

Once, we create the object, we go ahead and assign the values for name, age and gender.

Finally, we print out the values for name, age and gender.


Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

1 thought on “Classes and Objects in Python”

Leave a Comment

Your email address will not be published. Required fields are marked *

    Table of contents

Scroll to Top