Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

How To Construct Classes In Python

4 min read

Python is a versatile, dynamic object-oriented programming language created by Guido Van Rossum and first released in 1991.

Object-oriented programming (OOP) allows programmers to create there own objects that have attributes and methods making the code more reusable and organized at a larger scale. Code utilizing classes is generally easier to read, understand, and maintain. The two main concepts of OOP are classes and objects:

Class: Class is basically a blueprint or a template for creating objects.

Object: Collection of arguments and methods which can be performed on those data. An object is nothing but an instance of the class.

Suppose you want to design a supercar, first you will create a blueprint which includes all its features and design, but you can't ride it after all it's just a blueprint, right? In order to ride the car, you have to build a real car based on that blueprint.

In Object-oriented programming class is like a blueprint which has characteristics of the objects, and a real car is an object of that blueprint, infinite number of objects can be created from a single class.

You might have already heard that, "Everything is an object in Python". Let's verify that,

>>> my_string = "This is a string"
>>> print(type(my_string))
<class 'str'>

The type of the variable containing sting returns str class which means every string in Python is an object of the string class similarly any data is an object of Python's built in classes.

Beside these built-in classes, we can also create our own classes these are called user-defined classes.

In this article, we will guide you through creating classes and objects in Python.

Class In Python

A class functions as a template/blueprint that defines the basic characteristics of a particular object. A class is made up of attributes (data) and methods (functions). A very basic class in Python would look like,

class My_class():
    def first_method(self):
        print("First method will print this")
    def second_method(self):
        print("Second method will print this")

A class in Python starts with the class keyword followed with a single space and the class name which by convention should start with a capital letter. Next, we have a pair of parenthesis and colon(:) at the end.

Note that, everything inside the class should be intended because Python relies on indentation to know which block of code belongs to the class. Inside this class, we have two methods.

Methods are functions defined inside the class, methods will always have the self argument which is a reference to the object made on this class. The self keyword is used to assign attributes and method and relate them to the actual class. This ensures that the methods can refer to the attributes and variables of the class. Self will always be the first parameter of any method but it need not to be the only one..

Objects In Python

An Object is an instance of a class, to create an object of a class in Python first we need to initialize the object as a class instance by setting it equal to class_name()

my_object = My_class()

After object initialization, we can use the methods of the class using the dot operator ( . ) which acts as a reference for attributes of the class. Since the attribute which we are calling here is a function rather say method we need to add parenthesis ( ) in the end just like you would do for a regular function call.



First method will print this

The Constructor Method

Classes have a special method called __init__ (for initialization) or Constructor method which runs whenever an object is initialized. The constructor method is always the first method of any class.  The general syntax for defining a class with constructor in Python,

class Class_name():    def __init__(self, param1, param2):        self.param1 = param1        self.param2 = param2    def some_method(self):        #perform some actions        print(self.param1)

Let's go back to My_class where we created a basic class and object, this time we will have a constructor in the class definition.

class My_class():    def __init__(self):        print("Constructor will print this")    def first_method(self):        print("First method will print this")    def second_method(self):        print("Second method will print this")my_object = My_class()my_object.first_method()


Constructor will print thisFirst method will print this

Notice how the constructor method printed out the string before the actual method?

This is how constructors work in Python we do not need to explicitly call it therefore, it is generally used to initialize mutual attributes for the objects of the class.

class Circle():    # class object attribute    pi = 3.14    # constructor    def __init__(self, radius):        self.my_radius = radius    # method    def area(self):        return (self.my_radius * self.my_radius * Circle.pi)# object initializationmy_circle = Circle(2)print(my_circle.area())



In the above class we have declared a class object attribute assigning the value of pi, now every method inside the class has access to pi.

Next, in the constructor, the radius is stored to the my_radius variable along with the self keyword which makes it accessible for any method in the class. The area method is simply returning the area of a circle for the given radius.

This article went through creating classes, instantiating objects initializing attributes with the constructor method hope you learned something new out of it. Have questions? Feel free to ask in comment section below.


Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read