Classes in Python, constructors, Inheritance (Guide)

Classes In Python:

Before Working and creating class in python, Let me give you a short description about Classes in Python. Basically, Classes is a blueprint of any object that you will be create.

Example: Assume, you want to create a String variable object in Python for name field. Then you will be write code something like this:

name = "hulas"

In above code, I’ve created an object called “name” from Python’s inbuilt class called “String“. Now, age can access all those inbuilt method of string class e.g len(), strip(), Etc.

As same like above, We can also create our own custom classes in Python. In which we could define different attributes as a functions. So, that whenever someone would be create an object from our Custom Class, then they will be able to access all those functions declared under that Classes.

Now, Let’s jump into the deep down guide of this Classes in Python.

Creating A Class in Python:

I’m going to explain each and every points through an example, so that you could understand easily.

Let’s create a class name Point, In which we will have different attributes(Functions) to draw different shape. Just like we have different function in String class to perform over string object.

Structure to Create a Class And Object in Python
#Creating Class
Class <class_name>:
      def <function_name>(self):
          ----Operations----

# Creating Object

object_name = class_name()
class_name.funtion_name()  # To Access Function

Now Let’s Create A Class Point and then I will define you each section one by one:

class Point:
    def circle_draw(self):
        print("Draw A Circle")

    def triangle_draw(self):
        print("Draw A Triangle")

    def rectangle_draw(self):
        print("Draw A Rectangle")


point1 = Point()

point1.circle_draw()
point1.triangle_draw()
point1.rectangle_draw()
Ans: 
Draw A Circle
Draw A Triangle
Draw A Rectangle

In this above code, You can see that I’ve created A Class called Point. In this Point Class, I’ve defined 3 functions – circle_draw(), rectangle_draw(), triange_draw(). Then, I’ve created an object name point1 from Point() class.

Now this point1 object could call all methods declared inside that class Point(). You can call these methods by using ‘.’ operator e.g object_name.method_name()

Now Let’s see some advance example, now we will use constructors to initialize objects with initial value.

Note: In Python, We use “self” in each functions as a Parameter. Because all the functions that are declared in Python should have at least one parameter.It’s also a reference to their respective object.

Constructors in Python Classes:

In Python, We also have a constructors that we can use in our class to initialize our objects with initial value.

Let’s suppose, we want to create a object of Point() class with initial values e.g x=1, y=2. Here, we can use constructor to initialize.

Constructors: Constructor is a special method(function) that call It self automatically, Whenever we will create an object.

Let me show you how to create a constructor in Class.

class Point:
      def __init__(self, x, y):
          self.x = x
          self.y = y

In constructor we do use __init__ method to initialize constructors. It’s also known as magic method that we will discuss in other article. For Now, Only remember that __init__ function we’ve used here to declare constructor inside a class.

Under __init__ function, we’ve declared two variables x and y. Because these value we want to invoke initially whenever someone will be create an object.

After then we used self.x and self.y to reference x and y variable of objects. Now you can also access these x and y data by using same “.” dot operator e.g: object_name.variable_name

class Point:
      def __init__(self, x, y):
          self.x = x
          self.y = y
       
      def draw(self):
          print(f"Point ({self.x}, {self.y})")

point_1 = Point(1,2)
point_1.draw()
Ans:
Point (1, 2)

In above code, You could see that I’ve initialized point_1 object by value 1 and 2. Now then I’ve called a method draw by using dot operator.

You can also create variables separately in program apart from constructors Like:

point_1.z = 3

You May Also Like: Python Django Playlist For Web Development(Read Here)

Inheritance in Classes

In Python, One class can inherit features of other Classes. It’s the one of the most important feature of objected oriented type of Programming languages.

Inheritance: In Inheritance, You can inherit all the methods of Parent class into Child class. So, that you don’t need to rewrite a same code in different classes.

You could inherit method of one class to another by using inheritance. Let me show this through an example:

Let’s create classes for different animals like:

Classes in Python, Inheritance and Constructors

Let’s create 3 different classes

  • Animal()
  • Dog()
  • Fish()

In Animal, we will define only one function e.g Eat(). Because we know that all types of animals eats something. After then we will define Walk() function, because all dogs walk and eat also.

As similar a fish can have also two functions like Swim() and Eat().

But here, we’ve noticed that Eat() function are common in each classes. Because any kind of animals ca eat. Therefore, instead of defining Eat() function in each classes simply we will inherit it from Animal class. Because Animal class has already had Eat() function defined.

Now, Here Animal class will be Parent or Base class. After Then the classes who inherited Eat() function from Animal will be know as Child Or Sub Classes.

To Inherit class You need follow format like this :

class Animal():
    def eat(self):
        print("Eat")  # Each type of Animal should eat

class Dog(Animal):  # Here We Inherited Eat Method of Animal by using Inheritance
    def walk(self):
        print("walk")

class Fish(Animal):
    def swim(self):
        print("swim")

dog = Dog()  
fish = Fish()

dog.eat()  
dog.walk()
 
fish.swim()
fish.eat()  
result: 

Eat
walk
swim
Eat

In the above code you could see that all child classes inherited base class Animal. To inherit any class in Python you use this syntax:

class child_class(base_class)

Same I used Animal as Base class and Fish and Dog as A child. Now fish and dog class can inherit Animal Eat() Function easily. You could access all methods of Animal class by using same dot operator.

I hope you all will like this article. Please share this with your friends and geeks. You can also follow or subscribe our blog via email to get notified with next update of future posts.

Thank’s To Read…

1 thought on “Classes in Python, constructors, Inheritance (Guide)”

  1. Pingback: Exception Handling in Python: An Introduction(GUIDE) - HK2LITE.COM

Leave a Comment