Python UNIT 5
Python UNIT 5
Programming
UNIT-1
UNIT 5
Prof. Somesh Nandi
Dept. of AIML
Prof. Narasimha Swamy S
RV College of Engineering
Department of AIML
Bengaluru
RV College of Engineering
Bengaluru-59 Go, Change the World
Outline
→Software Objects:
→Object-Oriented Programming:
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Python Classes
A class is considered as a blueprint of
objects.
class ClassName:
# class definition
Here, we have created a class named ClassName.
→Let's see an example,
→class Bike:
name = ""
gear = 0
→Here,
→Bike - the name of the class
→name/gear - variables inside the class with default values
"" and 0 respectively.
objectName = ClassName()
In the above example, we have created two objects employee1 and employee2
of the Employee class.
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Access Class Attributes Using
Objects
The . Notation is used to access the attributes of a class.
Example :
# define a class
class Bike:
name = ""
gear = 0
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Python Methods
A Python Function defined inside a class is called a method.
#Let's see an example,
# create a class
class Room:
length = 0.0
breadth = 0.0
study_room.calculate_area()
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Invoking Default Constructor in
Python
When you do not write the constructor in the class created,
Python itself creates a constructor during the compilation of
the program.
12
Invoking Method by Parameterized Constructor
When
in Python
the constructor accepts arguments along with self, it is known as
parameterized constructor.
These arguments can be used inside the class to assign the values to the data
members. Let's see an example:
Code: Explanation
•An object of the class Family is
class Family: created. It has a variable known
# Constructor - parameterized as members.
members=‘’
•When the object is created, a
def __init__(self, count):
print("This is parametrized constructor") parameter (here it is 10) is passed as
self.members = count arguments.
def show(self): •This parameter (10 as in the given
print("No. of members is", self.members) example) is taken up by the constructor
as the object is created.
object = Family(10) •The number 10 is assigned to the
object.show() variable count, which is further
assigned to self.members.
•The self.members can be used within
the class to print the data
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Methods in Python
There are two types of the Method in Python.
Class Method
The purpose of the class methods is to set or get the details (status)
of the class. That is why they are known as class methods.
They can’t access or modify specific instance data. They are bound to
the class instead of their objects. Two important things about class
methods:
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Methods in Python
class My_class:
@classmethod
def class_method(cls):
return "This is a class method."
we’ll create the instance of this My_class as well and try calling this
class_method():
obj = My_class()
obj.class_method()
class Methods In Python
We can access the class methods with the help of a class instance/object.
we can also access the class methods directly without creating an instance
or object of the class.
Class_name.Method_name().
i.e My_class.class_method()
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Methods in Python
A static method is bound to a class rather than the objects for that class. This
means that a static method can be called without an object for that class. This
also means that static methods cannot modify the state of an object as they are
not bound to it
Example:
class Calculator:
When we need some functionality not w.r.t an Object but w.r.t the complete class,
we make a method static. This is pretty much advantageous when we need to create
Utility methods as they aren’t tied to an object lifecycle usually
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Encapsulation in Python
Encapsulation in Python describes the concept of bundling data and methods within
a single unit.
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
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Encapsulation Example
In this example, we create an
Employee class by defining
employee attributes such as name
and salary as an instance
variable and implementing
behavior using work() and show()
instance methods.
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Access Modifiers in Python
Encapsulation can be achieved by declaring the data members and methods of
a class either as private or protected.
Protected data members are used when you implement inheritance and want to allow data members access to
only child classes.
Example: Protected member in inheritance.
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Private Member
To define a private variable add two underscores as a prefix at the start of a variable name.
Private members are accessible only within the class, and we can’t access them directly from the class objects.
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Access Private Member
Access Private member outside of a class using an instance method.
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.
Now the Student class has the same properties and methods as the Person class.
Use the Student class to create an object, and then execute the printname
method,this printname method was created in parent class.
x = Student(“varun", “sharma")
x.printname()
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Using Inheritance to Create New
Classes
Creating a Child Class & Inheriting from a Base
Class/Parent class:
Eg:
Code : Output:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
Pass
x = Student("Varun","Sharma")
x.printname()
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Using Inheritance to Create New
•
Classes
Using the Derived[child] Class, extending a parent Class through Inheritance:
• Extending a Derived Class method:
Code : Output:
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class')
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
# Create object of Car
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Polymorphism
It refers to the use of a single type entity (method, operator or
object) to represent different types in different scenarios
Example
num1 = 1
num2 = 2
print(num1+num2)
str1 = "Python"
str2 = "Programming"
print(“str1”+”str2”)
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Function Polymorphism in Python
There are some functions in Python which are compatible to run with
multiple data types.
One such function is the len() function. It can run with many data types
in Python. Let's look at some example use cases of the function.
Example
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
Class Polymorphism in Python
Polymorphism while creating class methods as Python allows different
classes to have methods with the same name.
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World
22PL1B01-Introduction to Python Programming Department of Artificial Intelligence and Machine Learning Go, Change the World