Python
Raakesh Kumar
19. Opps Concept in
Python
3
Python Opps Concept
▪ Like other general-purpose ▪ The object is related to real-word entities
programming languages, Python is also such as book, house, pencil, etc.
an object-oriented language since its ▪ The oops concept focuses on writing the
beginning. reusable code.
▪ It allows us to develop applications ▪ It is a technique to solve the problem by
using an Object-Oriented approach. creating objects.
▪ In Python, we can easily create and ▪ Major principles of object-oriented
use classes and objects. programming system are given below.
▪ An object-oriented paradigm is to ▪ Class, Object, Method, Inheritance,
design the program using classes and Polymorphism ,Data Abstraction,
objects. Encapsulation
4
▪ Class
▪ class is a user-defined data type that
contains both the data itself and the
methods that may be used to manipulate
it.
▪ Classes serve as a template to create
objects.
▪ A class is a prototype of a building.
▪ A building contains all the details about the
floor, rooms, doors, windows, etc.
▪ we can make as many buildings as we
want, based on these details.
5
▪ Hence, the building can be ▪ Example:
seen as a class, and we can ▪ class Person:
create as many objects of this
class.
▪ def __init__(self, name,
age):
▪ syntax:
▪ self.name = name
▪ class ClassName:
▪ self.age = age
▪ #statement_suite
▪ def greet(self):
▪ print("Hello, my name is "
+ self.name)
6
Introduction to opps in python
▪ Class ▪ Syntax
▪ The class can be defined as a
collection of objects. class ClassName:
▪ It is a logical entity that has some
<statement-1>
specific attributes and methods.
.
▪ For example: if you have an
employee class, then it should .
contain an attribute and method, <statement-N>
▪ i.e. an email id, name, age, salary,
etc.
7
Introduction to opps in python
▪ Object ▪ When we define a class, it needs to
The object is an entity that has state and create an object to allocate the
behavior. It may be any real-world memory. Consider the following
object like the mouse, keyboard, chair, example.
table, pen, etc.
▪ Everything in Python is an object, and
almost everything has attributes and
methods. All functions have a built-in
attribute __doc__, which returns the
docstring defined in the function source
code.
8
Introduction to opps in python
▪ Example: ▪ Output:
class car: ▪ Toyota 2016
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
9
Introduction to opps in python
▪ Object ▪ Method
▪ In the above example, we have ▪ The method is a function that is
created the class named car, associated with an object. In Python, a
and it has two attributes method is not unique to class instances.
modelname and year. Any object type can have methods.
▪ We have created a c1 object to
access the class attribute.
▪ The c1 object will allocate
memory for these values.
10
Introduction to Opps in python
Example :Object & Methods Output:
class Person: "Hello, my name is Ayan"
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
person1 = Person("Ayan", 25)
person1.greet()
11
Introduction to Opps in python
▪ Class and Instance Variables ▪ class Person:
▪ All instances of a class count = 0 # This is a class variable
exchange class variables. def __init__(self, name, age):
self.name = name # This is an
▪ They function independently of
instance variable
any class methods and may be
self.age = age
accessed through the use of
Person.count += 1 # Accessing the
the class name.
class variable using the name of the
class
person1 = Person("Ayan", 25)
person2 = Person("Bobby", 30)
print(Person.count)
▪ Output: 2
12
Introduction to Opps in python
▪ Python Constructor ▪ Constructors can be of two types.
▪ A constructor is a special type of ╺ Parameterized Constructor
method (function) which is used to ╺ Non-parameterized Constructor
initialize the instance members of ▪ Constructor definition is executed when
the class. we create the object of this class.
▪ In C++ or Java, the constructor has ▪ Constructors also verify that there are
the same name as its class, but it enough resources for the object to
treats constructor differently in perform any start-up task.
Python.
▪ It is used to create an object.
13
Introduction to Opps in python
Creating the constructor in python emp1.display()
class Employee: emp2.display()
def __init__(self, name, id): ▪ Output:
self.id = id ID: 101
self.name = name Name: John
def display(self): ID: 102
print("ID: %d \nName: %s" % (self.id, Name: David
self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
14
Introduction to Opps in python
▪ Python Non-Parameterized def show(self,name):
Constructor print("Hello",name)
class Student: student = Student()
# Constructor - non parameterized student.show("John")
def __init__(self):
print("This is non parametrized
constructor")
▪
15
Introduction to Opps in python
▪ Python Parameterized def show(self):
Constructor print("Hello",self.name)
class Student:
student = Student("John")
def __init__(self, name):
student.show()
print("This is
parametrized ▪ Output:
This is parametrized constructor
constructor") Hello John
self.name = name
16
Introduction to Opps in python
▪ Python Default Constructor ▪ Output:
class Student: ▪ 101 Joseph
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.na
me)
st = Student()
st.display()
17
Introduction to Opps in python
▪ More than One Constructor in st = Student()
Single class ▪ Output:
class Student:
▪ The Second Constructor
def __init__(self):
print("The First
Constructor")
def __init__(self):
print("The second
contructor")
18
Introduction to Opps in python
▪ Python Inheritance ▪ A child class can also provide its specific
implementation to the functions of the
▪ Inheritance is an important aspect of the
parent class.
object-oriented paradigm. Inheritance
provides code reusability to the program ▪ In python, a derived class can inherit base
because we can use an existing class to class by just mentioning the base in the
create a new class instead of creating it bracket after the derived class name.
from scratch. Consider the following syntax to inherit a
base class into the derived class.
▪ In inheritance, the child class acquires the
properties and can access all the data
members and functions defined in the
parent class.
19
Introduction to Opps in python
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
▪ Syntax d.bark()
d.speak()
class derived-class(base class):
<class-suite> Output:
dog barking Animal Speaking
20
Introduction to Opps in python
▪ Python Multi-Level inheritance
▪ Multi-Level inheritance is possible in
python like other object-oriented
languages.
▪ Multi-level inheritance is archived
when a derived class inherits another
derived class.
▪ There is no limit on the number of
levels up to which, the multi-level
inheritance is archived in python.
21
Introduction to Opps in python
▪ Syntax class Animal:
def speak(self):
class class1:
print("Animal Speaking")
<class-suite> class Dog(Animal):
class class2(class1): def bark(self):
print("dog barking")
<class suite>
class DogChild(Dog):
class class3(class2): def eat(self):
<class suite> print("Eating bread...")
d = DogChild()
Output: d.bark()
dog barking Animal Speaking Eating bread...
d.speak()
d.eat()
22
Introduction to Opps in python
▪ Python Multiple inheritance ▪ Syntax
▪ Python provides us the flexibility class Base1:
to inherit multiple base classes <class-suite>
in the child class. class Base2:
<class-suite> ……..
class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<class-suite>
23
Introduction to Opps in python
class Calculation1: d = Derived()
def Summation(self,a,b): print(d.Summation(10,20))
return a+b; print(d.Multiplication(10,20))
class Calculation2: print(d.Divide(10,20))
def Multiplication(self,a,b):
return a*b; Output:
class Derived(Calculation1,Calculation2): 30 200 0.5
def Divide(self,a,b):
return a/b;
24
Introduction to Opps in python
▪ Python Encapsulation ▪ This also helps to achieve data
▪ Encapsulation is one of the key features of hiding.
object-oriented programming. ▪ In Python, we denote private
▪ Encapsulation refers to the bundling of attributes using underscore as the
attributes and methods inside a single prefix i.e single _ or double __. For
class. example,
▪ It prevents outer classes from accessing
and changing attributes and methods of a
class.
25
Introduction to Opps in python
class Computer: def setMaxPrice(self, price):
def __init__(self): self.__maxprice = price
self.__maxprice = 900 c = Computer()
c.sell()
Output:
def sell(self): Selling Price: 900
Selling Price: 900
print("Selling Price: c.__maxprice = 1000 Selling Price: 1000
{}".format(self.__maxprice)) c.sell()
c.setMaxPrice(1000)
c.sell()
26
Introduction to Opps in python
class Polygon:
▪ Polymorphism # method to render a shape
▪ Polymorphism contains two words def render(self):
"poly" and "morphs". print("Rendering Polygon...")
▪ Poly means many, and morph means class Square(Polygon):
shape. # renders Square
▪ By polymorphism, we understand that def render(self):
one task can be performed in different print("Rendering Square...")
ways. class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")
27
Introduction to Opps in python
▪ # create an object of Square Output
Rendering Square... Rendering
▪ s1 = Square() Circle...
▪ s1.render()
▪ # create an object of Circle
▪ c1 = Circle()
▪ c1.render()
28
Method Overriding
▪ Example:
▪ When the parent class method is ▪ class Animal:
defined in the child class with some
specific implementation, then the
▪ def speak(self):
concept is called method overriding. ▪ print("speaking")
▪ We may need to perform method ▪ class Dog(Animal):
overriding in the scenario where the ▪ def speak(self):
different definition of a parent class
▪ print("Barking")
method is needed in the child class.
▪ d = Dog()
▪ d.speak()
▪ Output: Barking
29
Introduction to Opps in python
▪ Abstraction ▪ The classes with one or more
▪ Abstraction allows us to focus abstract methods are known
on what the object does as Abstract classes.
instead of how it does it. Some ▪ Whereas an abstract method is
of the features of abstraction declared but does not hold an
are: implementation.
▪ It only showcases the
necessary information to the
user.
30
Introduction to Opps in python
from abc import ABC, abstractmethod
▪ Benefits of Abstraction class Car(ABC):
▪ Abstraction provides several def mileage(self):
benefits, such as:
pass
▪ It helps in minimizing the
class Tesla(Car):
complexity of the code written.
def mileage(self):
▪ It makes the code reusable.
print("The mileage is 30kmph")
▪ It enhances security because it
hides sensitive information class Suzuki(Car):
from the user. def mileage(self):
print("The mileage is 25kmph ")
31
Introduction to Opps in python
class Duster(Car): t= Tesla ()
def mileage(self): t.mileage()
print("The mileage is 24kmph ") r = Renault() Output:
r.mileage() The mileage is 30kmph
The mileage is 27kmph
class Renault(Car): s = Suzuki() The mileage is 25kmph
def mileage(self): s.mileage() The mileage is 24kmph
print("The mileage is 27kmph ") d = Duster()
d.mileage()
32
Assertion
▪ In Python, the assert ▪ x = 10
statement is used for ▪ assert x > 5 # No error, since
debugging and testing the condition is True
conditions in your code.
▪ It allows you to check whether
a condition is True, and if it's
▪ assert x < 5, "x should be
greater than 5" # Raises
not, the program raises an
AssertionError with a message
AssertionError.
33
“
Code1
The End
”
34
Hello!
I am Raakesh Kumar
I am here because I love
Python.
You can reach me at
[email protected]
or
Group whatsapp.