OOPs with Python

User Defined Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

 

Syntax : 

def <func_name>(<args_list>) :
    <func_body>
    return <expression>

Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.

Default values indicates that the function argument will take that value if no argument value is passed during function call.

Default / Optional Arguments

def student(first, last= "."):
    first_name = first
    last_name = last
    print("Full Name : " + first_name + " " + last_name)

Example :

Remember one thing - If you are passing values of immutable types (eg. numbers, strings, etc.) to the called function then the called function cannot alter the values of arguments but if you are passing the values of mutable types (eg. lists, dictionaries) then called function would be able to make changes in them.

Pass By Reference / By Value ?

a, b = 5, 10

def swap(p, q):
    print("Values in the function before change :", p, q) 
    p, q = q, p
    print("Values in the function after change :", p, q) 

swap(a, b)
print("Original Values : ", a, b)

Example 1 : ( This code will act as a pass by value )

L =[1,2,3,4,5]

def alter(li):
    print("List in func before change : ", li)
    li[2] = 8
    print("List in func after change : ", li)

alter(L)
print("Original List : ", L)

Example 2 : ( This code will act as a pass by reference )

When a function call itself is knows as recursion. Recursion works like a loop but sometimes it makes more sense to use recursion than loop. You can convert any loop to recursion.

Here is how recursion works. A recursive function calls itself. As you’d imagine such a process would repeat indefinitely if not stopped by some condition. This condition is known as base condition.

A base condition is must in every recursive programs otherwise it will continue to execute forever like an infinite loop.

Recursion

Object Oriented Programming (OOPs)

The object oriented programming has been developed with a view to overcome the drawbacks of conventional programming approaches. The OOP approach is based on certain concepts that help it attain its goal of overcoming the drawbacks or shortcomings of conventional programming approaches.

 

General Concepts of OOPs are :

1. Data Abstraction and Data Hiding.

2. Data Encapsulation.

3. Modularity.

4. Inheritance.

5. Polymorphism.

1. Data Abstraction and Data Hiding :

Abstraction refers to the act of representing essential features without including the background details or explanations.

Data hiding refers to the act of hiding unrelevant details from users.

 

 

2. Modularity :

The act of partitioning the programs into individual components is called modularity. The justification for partitioning the program is that -

    i.    it reduces the complexity to some degree and

    ii.   it creates a number of well defined, documented boundaries within the program.

A module is a separate unit in itself. It can be compiled separately though it has connections with other modules.

3. Inheritance :

It is the capability of one class of things to inherit properties or capabilities from another class. It provides re-usability. It supports transitivity. In other words, this concept lets you derive new classes from the existing ones.

 

4. Encapsulation :

The wrapping up of data and operations / functions (that operate on the data) into a single unit (class) is known as Encapsulation.

 

5. Polymorphism :

Polymorphism is the ability for a message or data to be processed in more than one form. Polymorphism in programming languages is implemented through two following concepts :

    i.  Function Overloading. ( Not supported in python )

    ii. Operator Overloading.

A class is a blueprint that defines the common structure and  common behaviour of objects . In simple words, a class defines an outline, based on which actual objects are created. It is also termed as object factory because based on class's specification multiple objects of same type can be created.

 

Once a class is defined, multiple instances (objects) based on the class's specification can be created. Classes are just conceptual entities but objects are real entities. An object would have all the attributes defined in the class with a proper value attached to each, defining the real entity.

 

Classes And Instances

Example :

As you know by now that objects are the real entities encapsulating characteristics and behaviour as one unit. A python class is created by class definition as per following syntax :

Creating Classes And Objects

class <class_name> : 
    
    <suite of statements>

An object is created or instantiated by using the definition of a class. The syntax to create an object is given below :

<object_name> = <class_name>()

1 . Instance Variables

Instance variables (are also known as object variables) are the ones that are created for each object.

In other words, every object has individual copy of an instance variable.

Variables in a Class

class student :
    def __init__(self, rno, name, mks) :
        self.roll_no = rno
        self.name = name
        self.marks = mks
        

Now this class has three instance variables :

roll_no , name and marks

Consider the following class :

2 . Class Variables

Class variables are those variables for which only one copy is created per class and are available to all the class members .

class student :
    no_of_students = 0
    class_teacher = "Dr. Kavita"

    def __init__(self, rno, name, mks) :
        self.roll_no = rno
        self.name = name
        self.marks = mks
        student.no_of_students += 1

Now these are two class variables which are defined in class definition, outside all method definitions.

Consider the same class student :

The When we create classes in python, we can use some special methods for specific purposes. In this section, we are going to discuss three special methods available for classes.

There are  :

i.    The init method [ __init__( ) ]

ii.   The del method [ __del__( ) ]

Special Methods for Class

1. The __init__( ) method

The init method is a special method that gets invoked when an object is instantiated. It is also sometimes called as a constructor method, as it works like an object constructor, but it is not a real constructor like some other languages have.

The structure of an init method is like the one shown below :

class <class_name> :
    
    def __init__(self, <parameters>) :
        <suite of statements>

2. The __del__( ) method

The Like constructors, there is no real destructor but python offers a method __del__( ) that works like a destructor. It is called when an object is about to be destroyed. It is implicitly invoked i.e.,  automatically invoked by python when an object is delete, which is when the garbage collector decides that there are no more references to an object.

It takes the following form :

class <class_name> :
    :
    :
    def __del__(self) :
        <statements>

To call this method, we have to use this syntax :

del <object_name>

The methods in a class are like functions, but they are not called just functions. They are called methods or member-functions. In other words, functions defined inside the class and define its functionality are known as methods. 

 

There are generally two types of methods in a class :

i.    Instance Methods

ii.   Static Methods

Methods in a Class

Consider the following class :

class Bank :

    def transfer(self, target, amt) :
        self.limit = target
        self.amount = amt

    def deposit(self, amt) :
        self.amount = amt

    def withdraw(self, amt) :
        self.amount = amt

    def check_bal(self) :
        print("Total amount : " , self.amount)

To call the methods, we have to use this syntax :

1. Instance Methods

These are the methods that are invoked using instance name or object name. An instance method or member-function belongs to a  class and it is defined within a class. The first parameter in the definition of an instance method has to be reference "self". This parameter is automatically sent to the method at the time of calling.

<ObjectName>.<MethodName>()

Consider the following class :

class Account :
    no_of_accounts = 0

    def __init__(self):
        self.balance = 1000
        Account.no_of_accounts += 1

    @staticmethod
    def acc_info():
        print(Account.no_of_accounts, " accounts have been created.")

2. Static Methods

These A static method is a method which is designed to be called with a class name, i.e., as :

<class_name>.<method_name>()

In other words, static methods are the methods that do not involve a particular object, but somehow involve the class.

Some facts associated with static methods are :

No self parameter is received by a static method.

Some facts associated with static methods are :

1.

No self parameter is received by a static method.

The line before method definition must be @staticmethod , which is a decorator, i.e. , a special message telling python that this method is a static method, not an instance method.

Some facts associated with static methods are :

1.

2.

No self parameter is received by a static method.

The line before method definition must be @staticmethod , which is a decorator, i.e. , a special message telling python that this method is a static method, not an instance method.

Static method only works with static variables i.e. class variables.

Some facts associated with static methods are :

1.

2.

3.

It is the capability of one class of things to inherit properties or capabilities from another class. It provides re-usability. It supports transitivity. In other words, this concept lets you derive new classes from the existing ones.

Inheritance

Different Forms of Inheritance :

​​​​1. Single Inheritance

2. Multiple Inheritance

3. Hierarchical Inheritance

4. Multilevel Inheritance

5. Hybrid Inheritance

Thank You :)

OOPs with Python

By Vipin Kumar

OOPs with Python

Slides for the PyTalk 2 Seminar

  • 299