Python is an Object Oriented Programming Language.
What is OOPs:
OOPs is a Programming Technique / Programming Approach/ Software
development methodology.
Object orientation is a software development methodology (Programing
Approach) that is based on a Real-world system.
An object oriented program consists of classes and objects.
Let us understand the terms— class and objects.
What is a Python Class:
A class is a template / skeleton / blueprint for creating an object.
In the first image (A), it represents a blueprint of a house that can be considered as Class.
With the same blueprint, we can create several houses and these can be considered as Objects.
1 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Basic Building Block of OOPs:
1. Class
2. Object
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Core Principles of OOPS
3. Encapsulation
4. Abstraction
5. Inheritance
6. Polymorphism
In Real World, The Class is a set or category of things sharing Common
Characteristics or Qualities.
Each Item belonging to a specific category possesses the characteristics and
behaviors described within it.
If We Consider ‘Furniture’ as a Category then different types of furniture such as
table, chair , bench etc. can be referred to as items of Category ‘Furniture’.
In Software terms Category and Items are considered to be Class and Objects
respectively.
In Object Oriented Programming Approach, A Computer Program is considered
to be a set of various objects.
Which can complete the work together? Each Object is a separate part of the
program and interacts with the other part of the program in a controlled
manner.
2 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
++++++++++++++++++++++++++++++++++++++++++
What is an Object:
Object is a fundamental unit of Object Oriented Programming and represents
the real life entities.
In Object Oriented Programming the attempts are made to break a task into
Some components, called objects.
The Objects are further categorized in two ways.
1) Real World objects
2) Software objects
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Real World Object:
Real World Object is one that we experience or use in our day to day life.
Real World Object Features:
1) It is Visible to Us
2) It has Definite Shape and Size.
3) It can be brought in thoughts and figures.
Each Real World Object Contains Characteristics and Behaviors
The Characteristics Basically comprises the parts of its body or Specifications.
Whereas behavior is the purpose of its use or its function.
Mobile Phone:
A Mobile Phone can be defined as a real world object.
The Characteristics are
• Model
• Dial Pad
• App
The Behaviors are
• It is used to talk.
• It is used to browse internet
• It is also used for net banking.
4 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Table:
Similarly You Can Consider Table as an Object.
The Characteristics are.
• It has a plain glass/wood top.
• It has Four legs
• It is made up of wood.
The Behaviors are
• It is used to keep copies and books.
• It is used for study purposes.
• It is used to keep glasses and plates.
These are all above nonliving Objects. The living things are also
Considered as real world objects.
For Example a Student may be considered as an object.
The Characteristics of a student are:
• A Student is identified by his/her name
• Each Student Studies in a specific class.
• Each Student has been allotted a unique roll number.
The Behaviors of a student are:
• He/She goes to School/College.
• He/She appears for the examination.
• He/She takes part in different competitions.
5 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Software Objects:
A Software Object May Be defined as an object that is created while Writing a
python program.
The Characteristics and Behavior of real world objects are referred to as Data
Members and Member Functions (Methods) of Software Objects respectively.
Hence, Software Object is a Unique Combination of Data Members/State/Characterstics and
Functions (Method).
6 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Comparative Study of Real World Objects and Software Objects
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Que)
What are the differences between Class and Object?
Ans:
—--
1. A Group of elements have common properties and common
behaviours, here the group of elements is called a
Class.
Among the group of elements, an individual element
having
physical properties and physical behaviours is called an
Object.
2. Class is Virtual.
7 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Object is Real / physical.
3. Class is the virtual encapsulation of the properties
and behaviours.
Object is the physical encapsulation of the properties
and behaviours.
4. Class is Generalization.
Object is Specialization.
5. Class is a blueprint for the objects.
Object is an instance/result of the class.
6. Class is a Model/Prototype for all the objects.
Object is an instance /result of the class.
Class is the collections of the objects.
8 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
1) An Object is an entity that has Properties for identifying its State, Methods for Behavior.
=> Data associated at any given instance of time is the state of an object.
=> Every object will different from other objects either by state or behavior.
=> Object has a lifetime – It’s created, used and destroyed.
2) An object has the following characteristics:
It has a state(instance variable)
It represent behavior(instance method) such as deposit, withdraw etc.
It has a unique identity.
3) Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
9 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
What is a Class?
A class is a template / skeleton / blueprint for creating an object.
Class is the collection of the common type of the information.
Class is the collection of the objects that has common properties.
Class is basically used for classification.
In Python every thing is an object. To create objects we required some Model or Plan or
Blueprint, which is nothing but class.
We can write a class to represent properties (attributes) and actions (behavior) of object.
10 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Properties can be represented by variables actions can be represented by Methods.
Hence class contains both variables and methods.
11 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Within the Python class we can represent data by using variables.
There are 3 types of variables are allowed.
1. Instance Variables (Object Level Variables)
2. Static Variables (Class Level Variables)
3. Local variables (Method Level Variables)
Within the Python class, we can represent operations by using methods.
The following are various types of allowed methods
1. Instance Methods
2. Class Methods
3. Static Methods
12 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
What is Object:
Physical existence of a class is nothing but object. We can create any number of objects for a class.
Syntax to create object:
referencevariable = classname()
Ex:
s = Student()
What is Reference Variable:
The variable which can be used to refer object is called reference variable.
By using reference variable, we can access properties and methods of object.
Program:
Write a Python program to create a Student class and Creates an object to it.
13 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Call the method talk() to display student details.
Ex:
14 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
#Program to demonstrate constructor will execute only once per object:
class Test:
def __init__(self):
print("Constructor execution...")
def m1(self):
print("Method execution...")
15 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
t1=Test()
t2=Test()
t3=Test()
t1.m1()
[StudentDemo2.py]
class Student:
def __init__(self,x,y,z):
self.name=x
self.rollno=y
self.marks=z
def display(self):
print("Student Name:{}\nRoll No:{}\nMarks:{}".format(self.name,self.rollno,self.marks))
s1=Student("DD",101,70)
s1.display()
s2=Student("Dev",102,90)
s2.display()
16 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
17 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Overview of OOPs Terminology:
1. Class:
A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class
variables and instance variables) and methods, accessed via dot notation.
2. Data member:
A class variable or instance variable that holds data associated with a class and
its objects.
3. Class variable:
A variable that is shared by all instances of a class. Class variables are defined
within a class but outside any of the class's methods.
4. Instance variable:
A variable that is defined inside a method and belongs only to the current
instance of a class.
Following Analogy explains the difference between class
member & instance member.
India as a class has certain attributes such as Constitution, Government, Capital,
Currency etc. It also has certain behaviours such as it trades with other
countries, fight wars, makes friends etc.
These attributes & behaviour are examples of Class members.
18 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Each Indian as an object of class Indian has same attributes such as name, age,
qualification, address etc. value of these attributes may be different for
different Indians. All of these are example of Instance members.
Class members are made available to objects but instance member are never
made available to the class.
5. Instance: An individual object of a certain class.
6. Instantiation:
The Process of object creation is known as instantiation. The creation of an
instance of a class.
7. Method :
A special kind of function that is defined in a class definition and describes the
behavior of an object.
8. Object: A unique instance of a data structure that's defined by its class. An
object comprises both data members (class variables and instance variables) and
methods.
9. Inheritance: The transfer of the characteristics of a class to other classes that
are derived from it.
10. Operator overloading:
The assignment of more than one function to a particular operator.
19 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Need Of Class and Object:
We’ve looked at dictionaries as able to represent what _something_ is.
For example, this dictionary represents a student:
my_student =
'name': 'Dev Singh',
'grades': [70, 88, 90, 99]
"""
If we want to calculate the average grade of the student, we could create a
function to do so:
"""
def average_grade(student):
return sum(student['grades']) / len(student['grades'])
Ex:
my_student={
'name': 'Dev Singh',
'grades': [70, 88, 90, 99]
20 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
def average_grade(student):
return sum(student['grades']) / len(student['grades'])
result=average_grade(my_student)
print(result)
However, there is a flaw with this. This function is separate and unrelated from
the student.
(Ex. in a professional program, they could even be in different files),
but it depends on the student variable having a particular Structure.
* The `student` must be a dictionary; and
* There must be a `grades` key that must be a list or tuple, so that we can use
`sum()` and `len()` on them.
It would be great if we could have something inside our dictionary that would
return the average grade.
That means the function would live in the same place as the data, and then it’s
easier to see whether the data we require has changed or not.
Something /like/ this:
"""
my_student =
'name': 'DD Singh',
21 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
'grades': [70, 88, 90, 99],
'average': 0 # something here to calculate/but it is not okk
"""
It would be fantastic if we could do this, and naturally the `'average'` would have
to change when then `'grades` changes. It must be a function.
*There’s no way to do this in a dictionary*.
Ex:
We must use objects for this. We can begin by thinking of objects as things that
can store both data and functions that relate to that data.
class Student:
def __init__(self, new_name, new_grades):
self.name = new_name
self.grades = new_grades
def average(self):
return sum(self.grades) / len(self.grades)
When you have that class, you can create objects using it. Let’s do that first and
then explain exactly what is happening
22 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
student_one = Student('DD', [70, 88, 90, 99])
student_two = Student('Dev', [50, 60, 99, 100])
Ex:
class Student:
def __init__(self, new_name, new_grades):
self.name = new_name
self.grades = new_grades
def average(self):
return sum(self.grades) / len(self.grades)
student_one = Student('DD', [70, 88, 90, 99])
student_two = Student('Dev', [50, 60, 99, 100])
print(student_one.name)
print(student_two.name)
print(student_one.average());
print(student_two.average());
To create a new object, we use the class name as if it were a function call:
`Student()`.
23 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Inside the brackets, we put arguments that will map to the `__init__` method in
the `Student` class.
`Student('DD', [70, 88, 90, 99])`
maps to
`__init__(self, new_name, new_grades)`.
What you end up with is a /thing/ that has two properties, `name` and `grades`.
print(student_one.name)
print(student_two.name)
## Methods
> A method is a function which lives in a class.
The `average()` method in the Student class also has access to `self`, the current
object. When we call the method:
print(student_one.average())
What is really happening in the background is:
print(Student.average(student_one))
"""
As you can see, `student_one` is passed as the first argument (and that is what
`self` is in the method definition):
"""
def average(self):
24 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
return sum(self.grades) / len(self.grades)
So again, because `self` is `student_one`, `self.grades` is `student_one.grades`.
Thus:
* The sum of `self.grades` is the sum of `[70, 88, 90, 99]`: 347.
* The length of `self.grades` is 4.
The result will be `86.75`.
Defining class:
Class name in python is preceded with class keyword followed by colon ( : ).
Ex:
class Student:
Classes commonly contains data field to store the data and methods for defining
behaviors.
Also every class in python contains a special method called initializer (also
commonly known as constructors), which get invoked automatically every time
new object is created.
Ex:
def __init__(self, new_name, new_grades):
self.name = new_name
self.grades = new_grades
25 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
26 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
27 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
28 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Non Parameterized Constructor:
Ex:
#This Demo is for Non Parameterized Constructor
class Product:
def __init__(self):
self.name="I-Phone"
29 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
self.description="It's Awesome"
self.price=700000
#Driver Code
s1=Product()
print(s1.name)
print(s1.description)
print(s1.price)
s2=Product()
print(s2.name)
print(s2.description)
print(s2.price)
30 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Parameterized Constructor:
Ex:
class Course:
def __init__(self,name,ratings):
self.name=name
self.ratings=ratings
c1=Course("Java Core",[1,2,3,4,5])
31 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
print(c1.name)
print(c1.ratings)
c2=Course("Java Advance",[5,5,5,5,5])
print(c2.name)
print(c2.ratings)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Define an instance method [Course2.py]
32 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Ex:
class Course:
def __init__(self,name,ratings):
self.name=name
self.ratings=ratings
def average(self):
nor=len(self.ratings)
avg=sum(self.ratings)/nor
print("Avg ratings for\",self.name,"is",avg)
c1=Course("Java Core",[1,2,3,4,5])
print(c1.name)
print(c1.ratings)
c1.average()
c2=Course("Java Advance",[5,5,5,5,5])
print(c2.name)
print(c2.ratings)
c2.average()
33 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Define an instance method:
Create Getter and Setter methods
34 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Create Getter and Setter methods:
Defining static field:
All objects share class or static variables. An instance or non-static variables are
different for different objects (every object has a copy).
For example, let a Computer Science Student be represented by class CSStudent.
The class may have a static variable whose value is “cse” for all objects.
And class may also have non-static members like name and roll.
In C++ and Java, we can use static keywords to make a variable a class variable.
The variables which don’t have a preceding static keyword are instance variables.
The Python approach is simple; it doesn’t require a static keyword.
35 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
All variables which are assigned a value in the class declaration are class
variables. And variables that are assigned values inside methods are
instance variables.
Ex:
# Python program to show that the variables with a value
# assigned in class declaration, are class variables
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self,name,roll):
self.name = name # Instance Variable
self.roll = roll # Instance Variable
# objects of CSStudent class
obj1 = CSStudent('Amit', 1)
obj2 = CSStudent('Ravi', 2)
36 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
print(obj1.stream) # prints "cse"
print(obj2.stream) # prints "cse"
print(obj1.name) # prints "Amit"
print(obj2.name) # prints "Ravi"
print(obj1.roll) # prints "1"
print(obj2.roll) # prints "2"
# Class variables can be accessed using class name also
print(CSStudent.stream) # prints "cse"
# Now if we change the stream for just obj1 it won't be changed for obj2
obj1.stream = 'ece'
print(obj1.stream) # prints 'ece'
print(obj2.stream) # prints 'cse'
# To change the stream for all instances of the class we can change it directly
from the class
CSStudent.stream = 'mech'
print(obj1.stream) # prints 'ece'
print(obj2.stream) # prints 'mech'
37 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Count the Number of objects:
#This demo is for static variable
class ObjectCounter:
numOfOb=0
def __init__(self):
ObjectCounter.numOfOb+=1
@staticmethod
def displayCount():
print("Number of Objects is ",ObjectCounter.numOfOb)
#Driver Code
x=ObjectCounter()
y=ObjectCounter()
ObjectCounter.displayCount()
More examples of classes:
Ex:
class Movie:
def __init__(self, name, year):
self.name = name
38 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
self.year = year
"""
Parameter names (in `(self, name, year)`) hold the values of the arguments that
we were given when the method was called: `Movie(‘The Matrix’, 1994)`.
`self.name` and `self.year` are the names of the properties of the new object we
are creating.
They only exist within the `self` object, so it’s totally OK to have
`self.name = name`.
"""
## `self` ?
"""
It’s common in Python to call the “current object” `self`. But it doesn’t have to be
that way!
"""
class Movie:
def __init__(current_object, name, year):
current_object.name = name
current_object.year = year
"""
Don’t do this, for it will look very weird when someone reads your code (e.g. if
you work or go to an interview), but just remember that `self` is like any other
variable name—it can be anything you want. `self` is just the convention. Many
editors will syntax highlight it differently because it is so common.
39 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
"""
"""
In a class, not all methods are the same. Python sometimes makes a distinction
depending on the method name. Here’s one of these special methods:
"""
class Student:
def __init__(self, name):
self.name = name
"""
This method is different from other methods because it gets called automatically
for you when you create a new object.
"""
Ex:
my_student = Student('DD')
"""
What happens here is that a new object is created, and then the `__init__`
method is called with the new object as `self` and the string you passed as
`'name'`.
"""
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
40 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Inner Class in Python
A class defined in another class is known as inner class or nested class.
If an object is created using child class means inner class then the object can also
be used by parent class or root class.
A parent class can have one or more inner class but generally inner classes are
avoided.
We can make our code even more object oriented by using inner class.
A single object of the class can hold multiple sub-objects. We can use multiple
sub-objects to give a good structure to our program.
Ex:
First we create a class and then the constructor of the class.
After creating a class, we will create another class within that class, the class
inside another class will be called as inner class.
Ex:
41 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Ex:
# create a Color class
class Color:
# constructor method
def __init__(self):
# object attributes
print("outer class constructor")
self.name = 'Green'
self.lg = self.Lightgreen()
def show(self):
print("Name:", self.name)
# create Lightgreen class
class Lightgreen:
def __init__(self):
print("Inner class constructor")
self.name = 'Light Green'
self.code = '024avc'
42 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
def display(self):
print("Name:", self.name)
print("Code:", self.code)
#Driver Code
# create Color class object
outer = Color()
outer.show()
#Access/Use a Lightgreen inner class object
g=outer.lg
#inner class method calling
g.display()
43 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Why inner class?
For the grouping of two or more classes. Suppose we have two classes remote
and battery.
Every remote needs a battery but battery without remote won’t be used.
So, we make the Battery an inner class to the Remote. It helps us to save code.
With the help of the inner class or nested class, we can hide the inner class from
the outside world.
Hence, Hiding the code is another good feature of the inner
class.
By using the inner class, we can easily understand the classes
because the classes are closely related. We do not need to search
for classes in the whole code, they all are almost together.
Types of inner classes:
1) Multiple inner class
2) Multilevel inner class
Multiple inner class:
The class contains one or more inner classes is known as multiple inner class. We
can have multiple inner class in a class, it is easy to implement multiple inner
class.
44 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# Multiple inner class Demo
class Doctors:
def __init__(self):
self.name = 'Doctor'
self.den = self.Dentist()
self.car = self.Cardiologist()
def show(self):
print('In outer class')
print('Name:', self.name)
# create a 1st Inner class
class Dentist:
def __init__(self):
self.name = 'Dr. Nagendra'
self.degree = 'BDS'
def display(self):
print("Name:", self.name)
print("Degree:", self.degree)
45 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# create a 2nd Inner class
class Cardiologist:
def __init__(self):
self.name = 'Dr. Arun'
self.degree = 'MD'
def display(self):
print("Name:", self.name)
print("Degree:", self.degree)
# create a object of outer class
outer = Doctors()
outer.show()
# create a object of 1st inner class
d1 = outer.den
# create a object of 2nd inner class
d2 = outer.car
print() # For New Line
d1.display()
#outer.den.display()
print()
46 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
d2.display()
Multilevel inner class:
The class contains inner class and that inner class again contains another inner
class, this hierarchy is known as multilevel inner class.
[InnerClassDemo3.py]
# Example of Multilevel inner class
class Demo:
def __init__(obj):
# create a inner class object
obj.inner = obj.Inner()
def show(obj):
print('This is an outer class')
# create a 1st inner class
class Inner:
def __init__(self):
# create a inner class of inner class object
self.innerclassofinner = self.Innerclassofinner()
def show(self):
print('This is the inner class')
47 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# create a inner class of inner
class Innerclassofinner:
def show(self):
print('This is an inner class of inner class')
# create a outer class object
# i.e.Demo class object
outer = Demo()
outer.show()
print()
# create a inner class object
obj1 = outer.inner
obj1.show()
print()
48 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# create a inner class of inner class object
obj2 = outer.inner.innerclassofinner
obj2.show()
49 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Special Methods
## Other interesting special methods
# `len()`
Given an *iterable* (generally a list, tuple, set, or dictionary;
something you can iterate over)
`len()` gives you the number of elements.
Ex:
movies=['Ham Aapkey Hai Kon', 'Koi Mil Gaya']
print(type(movies))
print(movies.__class__) # what's this?
count=len(movies)
print(count) # 2
Note:
We can make `len()` work on our classes too, by adding the `__len__` method
50 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Ex:
#This demo is for len() method
class Garage:
def __init__(self):
self.cars = []
'''
def __len__(self):
return len(self.cars)
'''
# Driver Code
ford_garage = Garage()
ford_garage.cars.append('Ford Fiesta')
ford_garage.cars.append('Ford Figo')
print(len(ford_garage))
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
### Getting a specific item (square bracket notation)
"""
We can also use square bracket notation in our `Garage`:
"""
51 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class Garage:
def __init__(self):
self.cars=[]
def __len__(self):
return len(self.cars)
def __getitem__(self, i):
return self.cars[i]
#Driver Code
ford_garage=Garage()
ford_garage.cars.append('Fiesta')
ford_garage.cars.append('Figo')
print(len(ford_garage))
print(ford_garage[1]) # Figo
'''
for car in ford_garage:
print(car)
'''
52 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Note:-
"""
A great thing about this is now you can iterate over the garage using a for loop.
To do this you need both `__len__` and `__getitem__`:
"""
for car in ford_garage:
print(car)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
__repr__ and __str__ function
### String representation
"""
If you want to print your objects out (and sometimes during development it can
be handy, as we’ll see), we can use `__repr__` and `__str__`
* `__repr__` should be used to print out a string representing the object such that
with that string you can re-create the object fully.
* `__str__` should be used when printing the object out to a user, for example—
can be more descriptive or even miss out some details.
"""
53 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class Garage:
def __init__(self):
self.cars = []
def __repr__(self):
return f'Garage {self.cars}'
def __str__(self):
return f'Garage with {len(self.cars)} cars'
"""
You should implement at least `__repr__`.
In order to call these methods, you can:
"""
obj = Garage()
obj.cars.append('Fiesta')
obj.cars.append('Figo')
print(obj)
print(str(obj))
print(repr(obj))
Note:
When we have both method ( __repr__ and __str__ ) in our program in that case
priority goes to __str__ when we call print() method.
54 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class Garage:
def __init__(self):
self.cars = []
def __repr__(self):
return f'Garage {self.cars}'
def __str__(self):
return f'Garage with {len(self.cars)} cars'
garage = Garage()
garage.cars.append('Fiesta')
garage.cars.append('Figo')
print(garage)
#print(repr(garage))
#print(str(garage))
55 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
str() vs repr() in Python:-
str() and repr() both are used to get a string representation of object.
Ex of str() Method:
s = 'Hello, DD'
print(str(s))
print(str(2.0/11.0))
Output:
Hello, DD
0.181818181818
Ex of repr() Method
s = 'Hello, DD'
print(repr(s))
print(repr(2.0/11.0))
Output:
'Hello, DD'
0.18181818181818182
From the output, we can see if we print string using repr()
function then it prints with a pair of quotes and if we calculate a value we get
more precise value than str() function.
56 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Following are differences:
str() is used for creating output for end user/client while repr() is mainly used for
debugging and development.
repr’s goal is to be unambiguous and str’s is to be readable. For example, if we
suspect a float has a small rounding error, repr will show us while str may not.
repr() compute the “official” string representation of an object (a representation
that has all information about the abject) and str() is used to compute the
“informal” string representation of an object (a representation that is useful for
printing the object).
The print statement and str() built-in function uses __str__ to display the string
representation of the object while the repr() built-in function uses __repr__ to
display the object.
Ex:
import datetime
today = datetime.datetime.now()
# Prints readable format for date-time object
print(str(today))
# prints the official format of date-time object
print(repr(today))
57 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Output:
2021-02-26 08:52:53.684912
datetime.datetime(2021, 2, 26, 8, 52, 53, 684912)
str() displays today’s date in a way that the user can understand the date and
time.
repr() prints “official” representation of a date-time object (means using the
“official” string representation we can reconstruct the object).
Print objects of a class:
An object is an instance of a Class.
A class is like a blueprint while an instance is a copy of the class with actual
values.
When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behavior of the
class. But the values of those attributes, i.e. the state are unique
for each object. A single class may have any number of instances.
Ex:
#If no __repr__ method is defined then the default is used
58 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
# Driver Code
t = Test(1234, 5678)
print(t)
#Python uses __repr__ method if there is no __str__ method
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:% s b:% s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t)
59 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# Python program to demonstrate
# object printing
# Defining a class
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:%d b:%d" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is % s, " \
"b is % s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
# This calls __str__()
print(t)
# This calls __repr__()
60 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
print([t])
Introduction to Inheritance:
Inheritance enables a class to
=> Inherit data members(variables) and methods from another class.
=> Reuse the functionalities and capabilities of the existing class by extending a
new class from the existing class and adding new features to it.
61 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
=> The class that inherits the data members and methods from another class is
known as the subclass.
=> The class from which the subclass inherits is known as the superclass.
The superclass is also referred to as the Base class/Parent, and the subclass is
referred to as the Derived class/Child class.
You can create additional data members and methods to add more features in a
subclass.
A superclass can also be a subclass of another class.
Inheritance represents the IS-A relationship.
Why use Inheritance?
=> For Code Reusability.
=> For Method Overriding (Runtime Polymorphism/Dynamic Polymorphism).
62 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Inheritance allows programmer to create a general class first then later extend it
to more specialized class.
It also allows programmer to write better code.
Using inheritance, you can inherit all access data fields and methods, plus you can
add your own methods and fields, thus inheritance provide a way to organize
code, rather than rewriting it from scratch.
Syntax:
class SubClass(SuperClass):
# data fields
# instance methods
Ex:
class ColorTV(BlackAndWhiteTV):
#Variables
#Methods
Types of Inheritance:
1)Single Inheritance
2)Hierarchical Inheritance
3)Multi Level Inheritance
4)Hybrid Inheritance
5)Multiple Inheritance
63 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
1. Single Inheritance
when a single Sub class is inherited from a single super class then the inheritance
is called as single inheritance.
2. Hierarchical Inheritance:
When more than one Child classes are inherited from a single Parent class, then
that inheritance is called as hierarchical inheritance.
64 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
3.Multi Level Inheritance
When a sub class is inherited from another subclass, then that inheritance is
called as multi level inheritance.
4. Hybrid Inheritance
Any combination of single, hierarchical and multi level inheritances is called as
hybrid inheritance.
65 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
5. Multiple Inheritance
When a Sub class is inherited from more than one super class then that
inheritance is called as multiple inheritance.
Note:
Unlike languages like Java and C#, Python allows multiple inheritance i.e you can
inherit from multiple classes at the same time like this,
class Subclass(SuperClass1,SuperClass2, ...):
# initializer
# methods
Demos on inheritance:
# This demo is for Single Level Inheritance
class Parent:
def __init__(self):
print("I am the Parent Constructor")
66 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
def display(self):
print("I Provide Black And White Color")
class Child(Parent):
def __init__(self):
super().__init__()
print("I am the Child Constructor")
def myMethod(self):
print("Beep Beep")
#Driver Code
obj=Child()
obj.display()
obj.myMethod()
input("Please Enter Any Key To Continue")
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
67 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
# This demo is for Hierarchical Inheritance
class Animal:
def move(self):
print("I move therefore I am...")
class Human(Animal):
def move(self): #Overriding
super().move()
print("Humans can walk and run...")
class Fish(Animal):
def move(self): #Overriding
super().move()
print("Fishes can swim and dive...")
def main():
h1 = Human()
h1.move()
f1 = Fish()
f1.move()
68 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
#Driver code
if __name__ == "__main__":
main()
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ex:
# This demo is for Multiple Inheritance
class MySuperClass1:
def super1(self):
print("method_super1 method called")
class MySuperClass2:
def super1(self):
print("method_super2 method called")
class ChildClass(MySuperClass2,MySuperClass1):
def child_method(self):
print("This is child method")
#Driver Code
c=ChildClass()
c.child_method()
c.super1()
69 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class A:
def m(self):
print("m() from A....")
class B:
def m(self):
print("m() from B....")
class C(A,B):
pass
'''
def m(self):
print("m() from C....")
'''
obj1 = C()
obj1.m()
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
70 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class Student:
#Parameterized constructor
def __init__(self,name,school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
#Driver code
obj1 = Student("Dev", "IIT")
obj1.marks.append(20)
obj1.marks.append(90)
print(obj1.average())
"""
Imagine you’ve got a class like the above, and you want to create a similar class
with some extra functionality. For example, a student that not only has marks but
also a salary—a `WorkingStudent`:
"""
71 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class WorkingStudent:
def __init__(self, name, school, salary):
self.name = name
self.school = school
self.marks = []
self.salary = salary
def average(self):
return sum(self.marks) / len(self.marks)
obj2 = WorkingStudent("DD", "NIT", 5000)
"""
However you can see there’s a lot of duplication between our `Student` and
`WorkingStudent` classes.
Instead, we may choose to make our `WorkingStudent` extend the `Student`.
It keeps all the same functionality, but we can add more.
"""
--------------------------------------------------------------------------------------------------
72 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
"""
obj1 = Student("Dev", "IIT")
obj1.marks.append(20)
obj1.marks.append(90)
print(obj1.average())
"""
class WorkingStudent(Student):
def __init__(self, name, school, salary):
super().__init__(name, school)
self.salary = salary
73 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
obj2 = WorkingStudent("DD", "NIT", 5000)
obj2.marks.append(57)
obj2.marks.append(99)
print(obj2.average())
Note:
The Above program explains the Reusability.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
PROPERTY DACORATORS:
"""
By the way,notice how the `average()` function doesn’t take any inputs other than
`self`. There’s nothing in the brackets.In those cases, and if you think it makes
sense, we can make it into a property, just like `marks` and `salary`.
All we have to do is:
"""
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
74 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
@property
def average(self):
return sum(self.marks) / len(self.marks)
"""
Now the `average()` function can be used as if it were a property instead of
a method; like so:
"""
obj3 = Student("Lata", "RSPS")
obj3.marks.append(80)
obj3.marks.append(90)
print(obj3.average)
[PropertyDecoratorDemo.py]
"""
You can do that with any method that doesn’t take any arguments.
But remember, this method only returns a value calculated from the object’s
properties.
If you have a method that does things (e.g. save to a database or interact with
other things), it can be better to stay with the brackets.
75 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Normally:
* Brackets: this method does things, performs actions.
* No brackets: this is a value (or a value calculated from existing values, in the
case of `@property`).
"""
-------------------------------------------------------------------------------------------------------------
Need of the classMethod and staticMethod:
"""
We’ve looked at how we can define classes and methods, including some special
methods like `__init__` and `__len__`.
All these methods had something in common: the `self` parameter at the start.As
a reminder, here’s some code:
"""
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
76 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
"""
When we create a new object from the `Student` class and we call a method, we
are automatically passing in the `self` parameter:
"""
stu1 = Student('Amit', 'NIT')
stu1.marks.append(78)
stu1.marks.append(99)
print(stu1.average())
"""
This is identical to that last line:
"""
print(Student.average(stu1))
"""
When we do `object.method()`, Python is in the background calling
`Class.method(object)`, so that `self` is always the object that called the method.
Indeed, if we were to have two objects:
"""
77 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
stu1 = Student('Amit', 'NIT')
stu2 = Student('Prateek', 'IIT')
stu1.marks.append(78)
stu1.marks.append(99)
stu2.marks.append(134)
stu2.marks.append(156)
print(stu1.average())
print(stu2.average())
"""
In the first case, `self` would be the `stu1` object, and in the second case `self`
would be the `stu2` object.
Notice that this knowledge now lets us do some very weird stuff (not
recommended, as it’ll likely break things):
"""
Student.average('hello') # self is now 'hello', comment this out to run the rest of
the file.
"""
78 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Just remember `self` is a parameter like any other; and you can give it any value
you want. However, because the method is then accessing `’hello’.marks`, you’ll
get an error for the string doesn’t have that property.
Anyway, so why is this important?
The first type of method we’ve looked at is called “instance method”: one that
takes the caller object as the first argument (that’s `self`).
-------------------------------------------------------------------------------------------------------------
-------
classMethod and staticMethod:
There are two more types of method:
ClassMethod:
* One that takes the caller’s class as the first argument
and
StaticMethod:
* One that takes nothing as the first argument
"""
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## @classmethod
"""
Let’s look at the one that takes the caller’s class as the first argument.
"""
79 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
[ClassMethodDemo1.py]
class Foo:
@classmethod
def hi(cls):
print(cls.__name__)
#Driver Code
my_object=Foo()
my_object.hi() #prints Foo
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## @staticmethod
"""
Now one that takes nothing as the first argument.
"""
[StaticMethodDemo.py]
class Foo:
@staticmethod
def hi():
print("I don't take arguments!")
80 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
my_object = Foo()
my_object.hi()
"""
The `@...` is called a decorator. Those are important in Python. They are used to
modify the function directly below them.
"""
class FixedFloat:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'<FixedFloat {self.amount:.2f}>'
#Driver Code
number = FixedFloat(18.5746)
print(number) # 18.57
"""
We have this `FixedFloat` class that is really basic—doesn’t really do anything
other than print the number out to two decimal places with the class name.
81 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Imagine we wanted to get a new `FixedFloat` object which is a result of summing
two numbers together:
"""
class FixedFloat:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'<FixedFloat {self.amount:.2f}>'
def from_sum(self,value1, value2):
return FixedFloat(value1 + value2)
# Driver Code
number = FixedFloat(18.5746)
new_number = number.from_sum(19.575, 2.789)
print(new_number)
"""
82 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
This doesn’t make any sense, because we created a `FixedFloat` object
(`number`), and then proceeded to call an instance method to create a new
object.
But that instance method didn’t use `self` at all—so really the fact that it’s a
method inside a class is not very useful.
Instead, we could make it a `@staticmethod`. That way, we’re not getting `self`
but we can still put the method in the class, since it is _related_ to the class:
"""
[StaticMethodDemo1.py]
class FixedFloat:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'<FixedFloat {self.amount:.2f}>'
@staticmethod
def from_sum(value1, value2):
print("We are in FromSum() method")
return FixedFloat(value1 + value2)
83 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
static_number = FixedFloat.from_sum(19.575, 2.789)
print(static_number)
"""
That looks a bit better! Now we don’t have the useless parameter AND we don’t
need to create an object before we can call the method. Win-win! However, let’s
now include some inheritance.
We’ll create a `Currency` class that extends this `Float` class.
"""
[StaticMethodDemo2.py]
class Euro(FixedFloat):
def __init__(self, amount):
super().__init__(amount)
self.symbol = '€'
def __repr__(self):
return f'<Euro {self.symbol}{self.amount:.2f}>'
# Skip defining from_sum as that's inherited
"""
84 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
We’ve defined this new class that extends the `FixedFloat ` class. It’s got an
`__init__` method that calls the parent’s `__init__`, and a `__repr__` method that
overrides the parents’. It doesn’t have a `from_sum` method as that’s inherited
and we’ll just use the one the parent defined.
"""
euros = Euro(18.5963)
print(euros) # <Euro €18.59>
result = Euro.from_sum(15.76, 19.905)
print(result) # <FixedFloat 35.66>
"""
Oops! When we called the `Euro` constructor directly, we got a `Euro ` object with
the symbol. But when we call `from_sum`, we got a `FixedFloat ` object. Not what
we wanted!
In order to fix this, we must make the `from_sum` method return an object of the
class that called it—so that:
* `FixedFloat.from_sum()` returns a `FixedFloat ` object; and
* `Euro.from_sum()` returns an `Euro` object.
`@classmethod` to the rescue! If we modify the `FixedFloat` class:
"""
85 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
[StaticMethodDemo3.py]
class FixedFloat:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'<FixedFloat {self.amount:.2f}>'
@classmethod
def from_sum(cls, value1, value2):
return cls(value1 + value2)
class Euro(FixedFloat):
def __init__(self, amount):
super().__init__(amount)
self.symbol = '€'
def __repr__(self):
return f'<Euro {self.symbol}{self.amount:.2f}>'
"""
When we now call:
* `Euro.from_sum()`, `cls` is the `Euro` class.
86 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
* `FixedFloat.from_sum()`, `cls` is the `FixedFloat` class.
"""
print(Euro.from_sum(16.7565, 90)) # <Euro €106.75>
------------------------------------------------------------------------------------------------------------
Question 1:
All methods in a class must have self as the first parameter.
Ans:
False
-----------------------------------------------------------------
class method vs static method in Python
Class Method:
A class method is a method which is bound to the class and not the object of the
class.
They have the access to the state of the class as it takes a class parameter that
points to the class and not the object instance.
It can modify a class state that would apply across all the instances of the class.
For example, it can modify a class variable that will be applicable to all the
instances.
87 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Static Method:
A static method is also a method which is bound to the class and not the object of
the class.
A static method can’t access or modify class state.
It is present in a class because it makes sense for the method to be present in
class.
-----------------------------------------------------------------------------------------
A class method takes cls as first parameter while a static method needs no
specific parameters.
A class method can access or modify class state while a static method can’t access
or modify it.
In general , static methods know nothing about class state.
They are utility type methods that take some parameters and work upon those
parameters.
On the other hand class methods must have class as parameter.
We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.
When to use what:
We generally use class method to create factory methods.
Factory methods return class object (similar to a constructor) for different use
cases. We generally use static methods to create utility functions.
88 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Method Overriding:
When We have the same method in the parent class as well as in the child class
that process is known as method overriding.
Rules for Method Overriding:
1) method must have same name as in the parent class
2) method must have same parameter as in the parent class.
3) must be inheritance (IS-A) relationship.
Advantage of Method Overriding:
1) Method Overriding is used to provide specific implementation of a method that
is already provided by its super class.
2) Method Overriding is used for Runtime Polymorphism/Dynamic Polymorphism
89 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
[OverridingDemo1.py]
#This demo is for overriding
class Parent:
def display(self):
print("I Provide Black And White Color")
class Child(Parent):
def display(self):
super().display()
Parent().display()
print("I Provide Color")
90 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
#Driver Code
obj=Child()
obj.display()
[OverridingDemo2.py]
class Person:
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def __str__(self):
return self.first + " " + self.last + ", " + str(self.age)
class Employee(Person):
def __init__(self, first, last, age, sal):
self.sal = sal
super().__init__(first, last, age)
def __str__(self):
return super().__str__() + ", " + str(self.sal)
91 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
def main():
x = Person("Virat", "Kohli", 27)
print(x)
y = Employee("Mahendra", "Dhoni", 36, 5000)
print(y)
#Driver Code
if(__name__ == "__main__"):
main()
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
isinstance() function:
The isinstance() function checks if the object (first argument) is an instance or
subclass of classinfo class (second argument).
Syntax:
isinstance(object, classinfo)
The isinstance() returns:
True if the object is an instance or subclass of a class, or any element of the tuple ,
False otherwise
Ex:
92 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
class A():
def __init__(self):
self.__x = 1
def m1(self):
print("m1 method from A Class")
class B(A):
def __init__(self):
self.__y = 1
def m1(self):
print("m1 method from B class")
b1 = B()
print(isinstance(b1, B)) #True
print(isinstance(3.5, float)) #True
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
93 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Encapsulation:
Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP).
It describes the idea of wrapping data and the methods that work on data within
one unit.
This puts restrictions on accessing variables and methods directly and can prevent
the accidental modification of data.
To prevent accidental change, an object’s variable can only be changed by an
object’s method. Those types of variables are known as private variable.
A class is an example of encapsulation as it encapsulates all the data that is
member functions, variables, etc.
->Encapsulation involves packaging one or more components together.
->Encapsulation is a process wrapping data and related behavior together into a
single unit .ex. capsule that is mixed of several medicines.
94 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
->Encapsulation is defined as the process of enclosing one or more items within a
physical or logical package.
Consider a real-life example of encapsulation, in a company, there are
different sections like the accounts section, finance section, sales section
etc.
The finance section handles all the financial transactions and keeps
records of all the data related to finance.
95 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
Similarly, the sales section handles all the sales-related activities and keeps
records of all the sales.
Now there may arise a situation when for some reason an official from the
finance section needs all the data about sales in a particular month.
In this case, he is not allowed to directly access the data of the sales section.
He will first have to contact some other officer in the sales section and then
request him to give the particular data. This is what encapsulation is.
Here the data of the sales section and the employees that can manipulate them
are wrapped under a single name “sales section”.
Using encapsulation also hides the data. In this example, the data
of the sections like sales, finance, or accounts are hidden from any other section.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
We can create fully encapsulated class by making all the data member(variable)
private .
Now we can use setter and getter method to set and get the data in it.
Advantage of Encapsulation:
With the help of encapsulation we provide control over the data.
96 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
[EncapsulationDemo.py]
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
if(price > 1000):
print("Sorry It is not Allowed")
else:
self.__maxprice = price
#Driver Code
c=Computer()
c.sell()
c.__maxprice=2000 # change the price
print(c.__maxprice)
97 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
'''
c.sell()
price=int(input("Enter Yr Price")) #
c.setMaxPrice(price) # using setter function
c.sell()
'''
98 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
What's the meaning of underscores (_ & __) in Python variable names
class A:
def __init__(self):
self.a = "Public"
self._b = "Internal Use Only"
self.__c = "Name Mangling in Action" #private
def main():
x=A()
print(x.a) #Public
print(x._b) #Protected
#print(x.__c) #This is prob
print(x._A__c) #It is OKK
99 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
if __name__ == "__main__":
main()
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Abstraction:
Abstract class:
100 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
To create the Abstract class We Have to inherit ABC class From the abc module.
[AbstractDemo.py]
from abc import ABC,abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
101 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
print("non abstract method")
def move1(self):
print("hello sdjsdj ")
class Human(Animal):
def move(self):
print("hello")
h=Human()
h.move()
h.move1()
polymorphism:
Polymorphism is an important feature of an Object Oriented Programing
102 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)
It is inherited from two words
1)"Poly" means "many" and 2)"morph" means "form".
Ex:
-> An object in different forms and in each form, it exhibits(Show) the same
functionality but implemented in different ways.
-> When one task is performed by different ways i.e. known as polymorphism
Examples:
-> A Teacher can take a form of Sport Teacher or Language Teacher and in both
the forms it has the same functionality Teach, but the implementation of Teach
varies in both the objects.
Vehicle – Car or Scooter – Drive
Phone – Mobile Phone or Landline Phone – Speak
Figure – Circle or Square - Area
103 DD Sir Infomatics, Agra-Whats App No. 9760433226 Online Training Courses
C,DSA,Java,Python,Web Develoment ETC… Visit www.codewithddsingh.com
Prepared By DD Singh,Coding Career Expert(19+ Years Experience)