Unit IV
Unit IV
com
• Class: The class is a user-defined data structure that binds the data members and
methods into a single unit. Class is a blueprint or code template for object creation.
Using a class, you can create as many objects as you want.
• Object: An object is an instance of a class. It is a collection of attributes (variables) and
methods. We use the object of a class to perform actions.
Objects have two characteristics: They have states and behaviors (object has attributes
and methods attached to it) Attributes represent its state, and methods represent its
behavior. Using its methods, we can modify its state.
• State: An object has an attribute that represents a state of an object, and it also
Class Attributes
When we design a class, we use instance variables and class variables.
In Class, attributes can be defined into two parts:
• Instance variables: The instance variables are attributes attached to an instance
class Student:
# class variables
school_name = 'ABC School'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
iamriteshkandari 9259069231 [email protected]
s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)
# access class variable
print('School name:', Student.school_name)
# Modify instance variables
s1.name = 'Jessa'
s1.age = 14
print('Student:', s1.name, s1.age)
# Modify class variables
Student.school_name = 'XYZ School'
print('School name:', Student.school_name)
Class Methods
In Object-oriented programming, Inside a Class, we can define the following three
types of methods.
• Instance method: Used to access or modify the object state. If we
use instance variables inside a method, such methods are called instance
methods.
• Class method: Used to access or modify the class state. In method
Inside this method, we don’t use instance or class variable because this static
method doesn’t have access to the class attributes.
class Student:
# class variable
school_name = 'ABC School'
# constructor
def __init__(self, name, age):
# instance variables
self.name = name
self.age = age
iamriteshkandari 9259069231 [email protected]
# instance method
def show(self):
# access instance variables and class variables
print('Student:', self.name, self.age, Student.school_name)
# instance method
def change_age(self, new_age):
# modify instance variable
self.age = new_age
s1 = Student("Harry", 12)
# call instance methods
s1.show()
s1.change_age(14)
# call instance methods
s1.show()
Constructor
In object-oriented programming, A constructor is a special method used to create
and initialize an object of a class. This method is defined in the class.
• The constructor is executed automatically at the time of object creation.
the object.
Syntax of a constructor
def __init__(self):
# body of the constructor
Where,
• def: The keyword is used to define function.
the __init__() method. It’s usually named self to follow the naming convention.
class Student:
# constructor
# initialize instance variable
def __init__(self, name):
print('Inside Constructor')
self.name = name
print('All variables initialized')
# instance Method
def show(self):
print('Hello, my name is', self.name)
# create object using constructor
s1 = Student('Emma')
s1.show()
iamriteshkandari 9259069231 [email protected]
Types of Constructors
In Python, we have the following three types of constructors.
• Default Constructor
• Non-parametrized constructor
• Parameterized constructor
Default Constructor
Python will provide a default constructor if no constructor is defined. Python adds a
default constructor when we do not include the constructor in the class or forget to
declare it. It does not perform any task but initializes the objects. It is an empty
constructor without a body.
If you do not implement any constructor in your class or forget to declare it, the
Python inserts a default constructor into your code on your behalf. This constructor
is known as the default constructor.
It does not perform any task but initializes the objects. It is an empty constructor
without a body.
Note:
• The default constructor is not present in the source py file. It is inserted into
the code during compilation if not exists. See the below image.
• If you implement your constructor, then the default constructor will not be
added.
Example:
class Employee:
def display(self):
print('Inside Display')
emp = Employee()
emp.display()
Non-Parametrized Constructor
A constructor without any arguments is called a non-parameterized constructor.
This type of constructor is used to initialize each object with default values.
This constructor doesn’t accept the arguments during object creation. Instead, it
initializes every object with the same set of values.
iamriteshkandari 9259069231 [email protected]
class Company:
# no-argument constructor
def __init__(self):
self.name = "PYnative"
self.address = "ABC Street"
# a method for printing data members
def show(self):
print('Name:', self.name, 'Address:', self.address)
# creating object of the class
cmp = Company()
# calling the instance method using the object
cmp.show()
Parameterized Constructor
A constructor with defined parameters or arguments is called a parameterized
constructor. We can pass different values to each object at the time of creation
using a parameterized constructor.
The first parameter to constructor is self that is a reference to the being
constructed, and the rest of the arguments are provided by the programmer. A
parameterized constructor can have any number of arguments.
class Employee:
# parameterized constructor
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
# display object
def show(self):
print(self.name, self.age, self.salary)
# creating object of the Employee class
emma = Employee('Emma', 23, 7500)
emma.show()
kelly = Employee('Kelly', 25, 8500)
kelly.show()
iamriteshkandari 9259069231 [email protected]
Inheritance in Python
The process of inheriting the properties of the parent class into a child class is called
inheritance. The existing class is called a base class or parent class and the new class is
called a subclass or child class or derived class.
In this Python lesson, you will learn inheritance, method overloading, method overriding,
types of inheritance, and MRO (Method Resolution Order).
In Object-oriented programming, inheritance is an important aspect. The main purpose of
inheritance is the reusability of code because we can use the existing class to create a new
class instead of creating it from scratch.
In inheritance, the child class acquires all the data members, properties, and functions
from the parent class. Also, a child class can also provide its specific implementation to the
methods of the parent class.
For example, In the real world, Car is a sub-class of a Vehicle class. We can create a Car by
inheriting the properties of a Vehicle such as Wheels, Colors, Fuel tank, engine, and add
extra properties in Car as required.
Syntax
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Types Of Inheritance
In Python, based upon the number of child and parent classes involved, there are
five types of inheritance. The type of inheritance are listed below:
1. Single inheritance
2. Multiple Inheritance
3. Multilevel inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single inheritance
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
iamriteshkandari 9259069231 [email protected]
print('Inside Car class')
# Create object of Car
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()
Multiple inheritance
# Parent class 1
class Person:
def person_info(self, name, age):
print('Inside Person class')
print('Name:', name, 'Age:', age)
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('Inside Company class')
print('Name:', company_name, 'location:', location)
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
# Create object of Employee
emp = Employee()
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning')
Multilevel inheritance
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
iamriteshkandari 9259069231 [email protected]
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class')
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Hierarchical Inheritance
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
obj1.info()
obj1.car_info('BMW')
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
Hybrid Inheritance
class Vehicle:
def vehicle_info(self):
iamriteshkandari 9259069231 [email protected]
print("Inside Vehicle class")
class Car(Vehicle):
def car_info(self):
print("Inside Car class")
class Truck(Vehicle):
def truck_info(self):
print("Inside Truck class")
# Sports Car can inherits properties of Vehicle and Car
class SportsCar(Car, Vehicle):
def sports_car_info(self):
print("Inside SportsCar class")
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()
class Component:
# composite class constructor
def __init__(self):
print('Component class object created...')
# composite class instance method
def m1(self):
print('Component class m1() method executed...')
class Composite:
# composite class constructor
def __init__(self):
# creating object of component class
self.obj1 = Component()
print('Composite class object also created...')
iamriteshkandari 9259069231 [email protected]
# composite class instance method
def m2(self):
Output
Component class object created...
Composite class object also created...
Composite class m2() method executed...
Component class m1() method executed...
Polymorphism
Polymorphism in Python is the ability of an object to take many forms. In simple words,
polymorphism allows us to perform the same action in many different ways.
For example, Jessa acts as an employee when she is at the office. However, when she is at
home, she acts like a wife. Also, she represents herself differently in different places.
Therefore, the same person takes different forms as per the situation
# Car Object
car = Car('Car x1', 'Red', 20000)
car.show()
# Vehicle Object
vehicle = Vehicle('Truck x1', 'white', 75000)
vehicle.show()
Operator Overloading
Operator overloading in Python allows the programmer to change the behavior of an
operator based on the type of the operands being used. This means that the same operator
symbol can have different meanings for different data types.
For example, the "+" operator is used for both adding numbers and concatenating strings.
When the operands are integers, the "+" operator performs arithmetic addition, but when
the operands are strings, it performs string concatenation.
The following are some common operator overloading methods in Python:
• add(): This method is used to overload the "+" operator.
• sub(): This method is used to overload the "-" operator.
• mul(): This method is used to overload the "*" operator.
• truediv(): This method is used to overload the "/" operator.
• lt(): This method is used to overload the "<" operator.
• gt(): This method is used to overload the ">" operator.
For example, the following code demonstrates operator overloading by creating a class
"Point" with "x" and "y" coordinates and overloaded the "+" operator to add the x and y
coordinates of two points:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return ((self.x + other.x,self.y+other.y))
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3)
As the name suggests, we are overloading the methods, which means there would be
many methods with the same name within a class, but having a different number of
arguments.
class OverloadingExample:
def add(self,a,b):
print(a+b)
def add(self,a,b,c):
print(a+b+c)
a=OverloadingExample()
a.add(5,10)
a.add(5,10,20)
Note: Python does not support method overloading, this is because python always picks
up the latest defined method. We can still overload methods in python but it would be
of no use.
class OverloadingExample:
def add(self, x = None, y = None):
if x != None and y != None:
return x + y
iamriteshkandari 9259069231 [email protected]
elif x != None:
return x
else:
return 0
obj = OverloadingExample()
print("Value:", obj.add())
print("Value:", obj.add(4))
print("Value:", obj.add(10,20))
we don’t mention the function definition multiple times. Instead, we manipulate the
arguments using the same method repeatedly.
Method Overriding
In method overriding, we will have many methods, and this time the number of arguments
will also be the same.
Now you must be wondering how these methods are different from each other if their
name and signatures are the same. So, the answer is that they differ in location. Methods
will be placed in different classes.
class Class1:
def display(self):
print("Hello from Class1")
class Class2:
def display(self):
print("Hello from Class2")
c1 = Class1()
c2 = Class2()
c1.display()
c2.display()
Encapsulation
Encapsulation in Python describes the concept of bundling data and methods within a
single unit. So, for example, when you create a class, it means you are implementing
encapsulation. A class is an example of encapsulation as it binds all the data members
(instance variables) and methods into a single unit.
iamriteshkandari 9259069231 [email protected]
class Employee:
# constructor
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project
# method
# to display employee's details
def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
# method
def work(self):
print(self.name, 'is working on', self.project)
Public Member:
class Employee:
# constructor
def __init__(self, name, salary):
# public data members
self.name = name
self.salary = salary
# public instance methods
def show(self):
# accessing public data member
print("Name: ", self.name, 'Salary:', self.salary)
# creating object of a class
emp = Employee('Jessa', 10000)
# accessing public data members
print("Name: ", emp.name, 'Salary:', emp.salary)
# calling public method of the class
iamriteshkandari 9259069231 [email protected]
emp.show()
Private Member:
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
# creating object of a class
emp = Employee('Jessa', 10000)
# accessing private data members
print('Salary:', emp.__salary)
Lambda function:
A lambda function is a small anonymous function in Python. It can take any number of
arguments, but can only have one expression. The expression is evaluated and returned
when the function is called.
Characteristics of a lambda function:
1. Anonymous: Lambda functions do not have a name and are referred to as anonymous
functions.
2. Single Expression: A lambda function can only contain one expression, which is
evaluated and returned.
3. Inline Function: Lambda functions are often used as inline functions and are not
intended to be reused.
4. Arguments: A lambda function can take any number of arguments but only one
expression.
5. Return Value: The expression in a lambda function is automatically returned, without
the need for a return statement.
6. Limited use: Lambda functions are limited to small, one-off tasks, as they cannot
contain multiple expressions and statements.
Syntax:
lambda arguments: expression
This function accepts any count of inputs but only evaluates and returns only one output .
That means it takes many inputs but returns only one output.
Example:
add = lambda num: num + 4
print(add(6))
iamriteshkandari 9259069231 [email protected]
a=lambda x,y:(x*y)
print(a(4,5))