0% found this document useful (0 votes)
24 views21 pages

Unit IV

:1

Uploaded by

anmo14251425
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views21 pages

Unit IV

:1

Uploaded by

anmo14251425
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

iamriteshkandari 9259069231 riteshkandarics@gmail.

com

What is a Class and Objects in Python?

• 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.

In short, every object has the following property.


• Identity: Every object must be uniquely identified.

• State: An object has an attribute that represents a state of an object, and it also

reflects the property of an object.


• Behavior: An object has methods that represent its behavior.

Python is an Object-Oriented Programming language, so everything in Python is treated as


an object. An object is a real-life entity. It is the collection of various data and functions
that operate on those data.
For example, If we design a class based on the states and behaviors of a Person, then
States can be represented as instance variables and behaviors as class methods.
iamriteshkandari 9259069231 [email protected]

Create a Class in Python


In Python, class is defined by using the class keyword. The syntax to create a class is
given below.
Syntax
class class_name:
'''This is a docstring. I have created a new class'''
<statement 1>
<statement 2>
<statement N>

• class_name: It is the name of the class


• Docstring: It is the first string inside the class and has a brief description of the
class. Although not mandatory, this is highly recommended.
• statements: Attributes and methods

Example: Define a class in Python


class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession
# Behavior (instance methods)
def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)
# Behavior (instance methods)
def work(self):
print(self.name, 'working as a', self.profession)

Create Object of a Class


An object is essential to work with the class attributes. The object is created using
the class name. When we create an object of the class, it is called instantiation. The
object is also called the instance of a class.
Syntax
<object-name> = <class-name>(<arguments>)
Below is the code to create the object of a Person class
iamriteshkandari 9259069231 [email protected]
jessa = Person('Jessa', 'Female', 'Software Engineer')
The complete example:
class Person:
def __init__(self, name, sex, profession):
# data members (instance variables)
self.name = name
self.sex = sex
self.profession = profession
# Behavior (instance methods)
def show(self):
print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)
# Behavior (instance methods)
def work(self):
print(self.name, 'working as a', self.profession)
# create object of a class
jessa = Person('Jessa', 'Female', 'Software Engineer')
# call methods
jessa.show()
jessa.work()

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

of a class. We define instance variables in the constructor ( the __init__() method


of a class).
• Class Variables: A class variable is a variable that is declared inside of class, but

outside of any instance method or __init__() method.

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

implementation, if we use only class variables, then such type of methods we


should declare as a class method.
• Static method: It is a general utility method that performs a task in isolation.

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()

Pass Statement in Class


In Python, the pass is a null statement. Therefore, nothing happens when the pass
statement is executed.
The pass statement is used to have an empty block in a code because the empty
code is not allowed in loops, function definition, class definition. Thus, the pass
statement will results in no operation (NOP). Generally, we use it as a placeholder
when we do not know what code to write or add code in a future release.
For example, suppose we have a class that is not implemented yet, but we want to
implement it in the future, and they cannot have an empty body because the
interpreter gives an error. So use the pass statement to construct a body that does
nothing.
Example
class Demo:
pass
In the above example, we defined class without a body. To avoid errors while
executing it, we added the pass statement in the class body.
iamriteshkandari 9259069231 [email protected]

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 primary use of a constructor is to declare and initialize data

member/ instance variables of a class.


For example, when we execute obj = Sample(), Python gets to know that obj is an
object of class Sample and calls the constructor of that class to create an object.
In Python, Object creation is divided into two parts in Object Creation and Object
initialization
• Internally, the __new__ is the method that creates the object

• And, using the __init__() method we can implement constructor to initialize

the object.
Syntax of a constructor
def __init__(self):
# body of the constructor
Where,
• def: The keyword is used to define function.

• __init__() Method: It is a reserved method. This method gets called as soon as

an object of a class is instantiated.


• self: The first argument self refers to the current object. It binds the instance to

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()

What is Composition (Has-A Relation)


It is one of the fundamental concepts of Object-Oriented Programming. In this
concept, we will describe a class that references to one or more objects of other
classes as an Instance variable. Here, by using the class name or by creating the
object we can access the members of one class inside another class. It enables
creating complex types by combining objects of different classes. It means that a
class Composite can contain an object of another class Component. This type of
relationship is known as Has-A Relation.

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):

print('Composite class m2() method executed...')


# calling m1() method of component class
self.obj1.m1()

# creating object of composite class


obj2 = Composite()

# calling m2() method of composite class


obj2.m2()

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

Polymorphism with Inheritance


Polymorphism is mainly used with inheritance. In inheritance, child class inherits the
attributes and methods of a parent class. 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.
Using method overriding polymorphism allows us to defines methods in the
child class that have the same name as the methods in the parent class. This process of re-
implementing the inherited method in the child class is known as Method Overriding.

Advantage of method overriding


• It is effective when we want to extend the functionality by altering the inherited
method. Or the method inherited from the parent class doesn’t fulfil the need of a child
class, so we need to re-implement the same method in the child class in a different
way.
iamriteshkandari 9259069231 [email protected]
• Method overriding is useful when a parent class has multiple child classes, and one of
that child class wants to redefine the method. The other child classes can use the
parent class method. Due to this, we don’t need to modification the parent class code
In polymorphism, Python first checks the object’s class type and executes the
appropriate method when we call the method. For example, If you create the Car object,
then Python calls the speed () method from a Car class.

Let’s see how it works with the help of an example


class Vehicle:
def __init__(self, name, color, price):
self.name = name
self.color = color
self.price = price
def show(self):
print('Details:', self.name, self.color, self.price)
def max_speed(self):
print('Vehicle max speed is 150')
def change_gear(self):
print('Vehicle change 6 gear')

# inherit from vehicle class


class Car(Vehicle):
def max_speed(self):
print('Car max speed is 240')
def change_gear(self):
print('Car change 7 gear')

# Car Object
car = Car('Car x1', 'Red', 20000)
car.show()

# calls methods from Car class


car.max_speed()
car.change_gear()

# Vehicle Object
vehicle = Vehicle('Truck x1', 'white', 75000)
vehicle.show()

# calls method from a Vehicle class


iamriteshkandari 9259069231 [email protected]
vehicle.max_speed()
vehicle.change_gear()

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)

The output of this code will be:


(4, 6)
iamriteshkandari 9259069231 [email protected]
Method overloading allows multiple methods in the same class to have the same name
but different parameters. Method overriding allows a parent class and a child class to have
methods with the same name and same parameters. The child class method will override
the parent class method.
Difference between Method overloading and Method overriding

Method Overloading Method Overriding


Method with same name but different Method with same name and same
number of arguments number of arguments
Inheritance is optional Inheritance required
Takes place in methods within a class Methods reside in different classes
Can be done within a class At least 2 classes are required
Binding of overloaded methods is done at Binding of overridden methods is done
compile-time; hence it is part of compile- at run-time; hence it is part of run-time
time polymorphism polymorphism
Static method can be overloaded Static methods cannot be overridden
Increases code reusability Used in implementation of specific
scenarios
Relates with Polymorphism Relates with Inheritance

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)

# creating object of a class


emp = Employee('Jessa', 8000, 'NLP')

# calling public method of the class


emp.show()
emp.work()
iamriteshkandari 9259069231 [email protected]

Access Modifiers in Python


Encapsulation can be achieved by declaring the data members and methods of a class
either as private or protected. But In Python, we don’t have direct access modifiers like
public, private, and protected. We can achieve this by using
single underscore and double underscores.
Access modifiers limit access to the variables and methods of a class. Python provides
three types of access modifiers private, public, and protected.
• Public Member: Accessible anywhere from otside oclass.
• Private Member: Accessible within the class
• Protected Member: Accessible within the class and its sub-classes

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))

You might also like