Skip to content

Object Oriented Programming in Python – An Intro for Beginners

Object oriented programming in Python

In this tutorial we will get a basic understanding of Object Oriented Programming in Python . Python is an Object Oriented Programming(OOP) language. Almost everything is an object in Python. So far we have talked about procedure oriented programming (POP) where we have repeatedly used a code with the help of function which fulfills a basic principle of programming that is DRY (Don’t Repeat Yourself). The DRY principle is also fulfilled by creating classes in object oriented programming. Object Oriented Programming also enhances code understanding.

What is Object Oriented Programming

Object Oriented Programming (OOP) is a method by which we can arrange different properties and behavior of an object in the same program.

What is class , instance and object in Python

Class is a blueprint for creating objects that can be used to create one or more objects.

Any Object in a class is called an Instance of that class.

Any specific instance of a class is called the Object of that class.

Now we will try to understand the class, instance and object with the help of an example. When we go to apply for a job exam, we are first given an empty form, we fill-up that empty form and apply for the job exam. The empty form is a class that is same for everyone. But after different candidates fill-up that empty form, each form becomes different because the information of each examinee is different. That filled-up form is the object which is different for everyone. So more than one object can be created from one class and each object is an instance of that class.

A sample class
A sample object of the above class

Syntax for creating a class in Python

class class_name:
     "class docstring"
     statements 

Structure of a class in Python

The structure of any python class is shown in the list below –

  • Any class starts with class keyword followed by the name of the class.
  • Any class header will end with a colon (:) and the next code block will be indented.
  • We can use docstring in the first statement of a class. This is optional. With the help of docstring we know for what reason the class will be used . With the help of __doc__ attribute we can access the docstring of any class.

Syntax for creating a object in Python

object_name = class_name()

Example 1: Using docstring in Python class

# creating a class named Myclass
class Myclass:
    '''This is myclass'''
    a = 10
    
# creating a object of class Myclass
myobject = Myclass()

# accessing docstring using classname
print(Myclass.__doc__)

# accessing docstring using objectname
print(myobject.__doc__)
This is myclass
This is myclass

In the above code, a class named Myclass has been created in which a docstring has been written. Then an object of Myclass named myobject has been created. We can access the docstring of any class with both class and object. Which is shown in the next part of the code.

What is class variable and instance/object variable

A class variable is a variable that is defined within a class but outside of a class method. The class variable can be accessed by that class and all objects of that class. But if we want to change the value of a class variable, it can only be changed by class, It cannot be changed by any object. Class variables are also called class attribute and class property .

An instance/object variable is a variable that is defined within a class method or after an object creation outside the class. It can only be accessed and changed by the object. Object variables are also called object attribute and object property .

Example 1: Creating class variable and object variable in a Python class

#creating a class named Myclass
class Myclass:
    # creating class variable
    total_student = 10

In the above code, first a class named Myclass has been created with a class variable named total_student.

#creating two object of class Myclass
sourav = Myclass()
sudipta = Myclass()

Then two objects of Myclass class named sourav and sudipta have been created.

#creating object variable
#for sourav
sourav.roll_no = 8
sourav.age = 26

#for sudipta
sudipta.roll_no = 7
sudipta.age = 27

Then two instance variables roll_no and age have been created for each object. roll_no of sourav and sudipta is 8 and 7 . age of sourav and sudipta is 26 and 27

#accessing class variable
#using classname
print(Myclass.total_student)

#using object name
print(sourav.total_student)
print(sudipta.total_student)
10
10
10

Then the class variable is accessed by the name of the class and the object , which has printed 10 in each case.

Built-in class attribute in Python

Python has some built-in class attributes that we can use by adding the dot (.) operator to the class_name. They are given through a list –

  • __dict__ = Returns a dictionary with key as name of various attribute and value as corresponding value of that attribute .
  • __doc__ = If the class has docstring then it will return the docstring else None .
  • __name__ = Returns the class_name .
  • __module__ = If the class is in a module, it returns the name of the module else “__main__”.
# __dict__ attribute
# using class name
print(Myclass.__dict__)

# using object name
print(sourav.__dict__)
{'__module__': '__main__', 'total_student': 10, '__dict__': <attribute '__dict__' of 'Myclass' objects>, '__weakref__': <attribute '__weakref__' of 'Myclass' objects>, '__doc__': None}
{'roll_no': 8, 'age': 26}

This code is the continuation of the previous code . Here we have applied __dict__ attribute to the Myclass class and sourav object of Myclass class . In both the cases it has printed a dictionary which contains all the attributes with their value that can be accessible from the class or the object .

# __doc__ attribute
print(Myclass.__doc__)
None

As during definition we have not specified any docstring so it just returned None .

# __name__ attribute
print(Myclass.__name__)
Myclass

As the name of the class is Myclass so it returned Myclass .

# __module__ attribute
print(Myclass.__module__)
__main__

As the class is not part of any module so it returned __main__ .

What is object method in Python

The object method is the behavior of the object, which can only be accessed through an object.

Syntax of a object method in Python

def method_name(self,parameters):
    statements

Parameters of object method in Python

The first parameter in the object method is always self. Then we need to pass the required parameters. self is a reference to a given object. We can use anything in place of self but whatever it is the first parameter is always treated as a reference to the given object. But only self is used as convention.

Since self is used as a convention, all programmers use self as the first parameter in the object method. So if we read someone else’s program or someone else reads our program and there is something written in the first parameter of the object method other than self then we may get confused. So we will always use self in the first parameter of the object method.

Calling a object method in Python

object_name.method_name(parameters)

Example 1: Defining a object method in a Python class

# creating a class named Car
class Car:
    # here we use obj in the position of self
    # defining object method start_car
    def start_car(self):
        print("car has started")
        self.speed = 0

In the above code, a class named Car has been written with a object method named start_car . When defining start_car takes one parameter . In the start_car method a variable named speed has been created whose value is 0 . Since the speed variable is defined in the object method, speed is an object variable that can only be accessed with an object.

# creating a object of class Car
BMW = Car()
# calling the object method
BMW.start_car()
# we can also call this as
Car.start_car(BMW)
car has started
car has started

Now an object named BMW has been created and its start_car method has been called. Notice that we did not use any argument in the start_car method where we used a parameter while defining but the program did not show any error. Here, in fact, the object i.e. BMW has been treated as an argument. Which we can see in the next line when we run the same method by typing Car.start_car(BMW) which gives the same output. So object itself is treated as the first argument of any object method .

# from start_car method a object variable
# speed is created
print(BMW.speed)
0

What is constructor in Python

Constructor is a special object method, which is automatically called while creating the object.

Syntax of constructor in Python

def __init__(self,parameters):
    statements

Example 1: Defining a constructor in a Python class

#creating a class
class Myclass:
    #creating a constructor
    def __init__ (self, name, age, roll_no):
        #creating object variables
        self.name = name
        self.age = age
        self.roll = roll_no

In the above code a class is written and a constructor is defined in it which takes three more parameters besides self. When we have written self.name = name then a new object variable name( name from left side) will be created after object creation with value as name (name from right side ) which is passed as a parameter . In case of self.roll = roll_no name of the object variable will be roll and value will be roll_no .

#creating a object
# sudipta = Myclass()  #error
sudipta = Myclass("sudipta", 26, 6)

#accessing object variable
print(sudipta.name)
print(sudipta.age)
print(sudipta.roll)
sudipta
26
6

Since the constructor is automatically called, the value of the constructor’s parameters has to be passed as an argument when we create the object which we have done here. And this has created three object variables that we can access through the object. If we don’t pass constructor’s parameter during object creation it will raise an error .

What is class method in Python

The class method is the behavior of the class which can be accessed by any object of that class besides the class. With class method we can change the value of class attribute which is not possible by object method .

Syntax of class method in Python

@classmethod
def method_name(cls,parameters):
    statements

Before defining any class method we have to use @classmethod otherwise the method will be treated as object method. Some similarities between object method and class method are given below in the form of list –

  • Just as the first parameter is always treated as a reference to an object when defining an object method, so the first parameter is always treated as a reference to a class when defining a class method.
  • Just as we can use any other word in place of self in the first parameter during object method definition, we can use any other word in place of cls in the first parameter in class method definition. But self, cls are programming convention and we will always use cls in the first parameter of class method.

Note :

We have known previously that class variables can be modified only with class_name but using class method we can also change class variables with object_name.

Calling a class method in Python

class_name/object_name.(parameters)

Example 1: Defining a class method in Python class

#creating a class
class Myclass:
    #creating a class variable
    total_student = 15
        
    #creating a class method
    @classmethod
    def set_total_student (self, no_of_students):
        #modify the value of class variable
        self.total_student = no_of_students

In the above code we have defined a class named Myclass . It has a class variable total_student and a class method set_total_student . This method will change the value of class variable with the given value .

# creating an object
sourav = Myclass()
# accessing class variable
print(Myclass.total_student)
15

After that we have created an object named sourav of the Myclass class . Then accessing the class variable total_student using class name which printed 15 in the output .

# changing the class variable using class name
Myclass.set_total_student(20)

# accessing class variable
print(Myclass.total_student)

# changing the class variable using object name
Myclass.set_total_student(25)

# accessing class variable
print(Myclass.total_student)
20
25

After that we have called the class method using class name with value 20 which has changed the value of class variable total_student . Then we have printed the class variable which printed 20 in the output .

Then we have again called the class method using object name with value 25 which has changed the value of class variable total_student . After that we have printed the class variable which printed 25 in the output .

What is static method in Python

static method is a general function used in a class. Before defining any static method we have to use @staticmethod otherwise the method will be treated as object method.

As the first parameter self of the object method is the reference of the object and the first parameter cls of the class method are used as reference of the class, there is no such reference in the case of static method. The number of parameters are used when defining a static method, the same number of arguments should be used when calling it.

The static method can be accessed by either class or object, it is used for any utility work.

Syntax of static method in Python

@staticmethod
def method_name(parameters):
    statements

Calling a static method in Python

class_name/object_name.(parameters)

Example 1: Defining a static method in Python class

#creating a class
class Student:
    #creating a class variable
    total_marks = 400
    #creating a constructor
    def __init__ (self, name, marks):
        #creating object variable
        self.name = name
        self.marks = marks
        
    #creating a static method
    @staticmethod
    def percentage (mark, total_mark):
        return (mark / total_mark) * 100

In the above code, a class named Student is defined which have a class variable named total_marks, two object variables named name and marks and a static method called percentage.

#creating a object  
partha = Student("Partha", 340)
#calling the static method percentage
print(partha.percentage(partha.marks, partha.total_marks))
print(Student.percentage(partha.marks, partha.total_marks))
85.0
85.0

Then an object named partha is created and the static method percentage is called twice in a row with the help of object name and class name which returns 85.0 in both cases.

Notice that the percentage method is only returning the percentage of a student, there is no need for a class reference or an object reference, so there is no need to use the class method or object method. In these cases we will use only static method.

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply