Python Programming Notes
Python Programming Notes
For printing a message in python we use a builtin function called print() function in
which we pass the string in the arguments during calling of the print() function in
your python program. Just take an example of the string: "Hello Bhaiyo!". As we
know that, string is enclosed with double quotation mark.
Hello Bhaiyo
Variables
There is a concept of variable comes in programming. The variable is a container
that contains value of any data type whether it is string, integer, boolean, list, tuple
and so on. The variable is the name of the memory location where the value of the
variable is stored. There is no way to declare variable in python. The variable is
created in python when you assign value to the variable.
1. Name of the variable starts with starts with alphabets and underscore.
2. Do not start name of the variables with numbers.
3. Keywords is not considered as the name of the variable.
4. Name of the variable is either alphabetic or alphanumeric.
I always recommend to write the name of the variable in camel case method or
snake case method. In camel case method if we have the name of variables
contains more than one word then we write first letter of the first word in small
letter and then first letter of other words after first word in capital letter. In snake
case we underscore between the words of the variables.
Comments in Python
Here, there is one more concept about the comment which you must know. The
comment starts with “#” sign as it comment only single line. The interpreter
ignores the comment line from the code. The comment is mainly used to describe
the code to make reader or coder understand. There is one more type of comment
is multiline comment which is enclosed with triple quotation marks. [“”” Hi “””]
In [ ]: #Multiline Comment
"""
Hello
Guys
"""
5
Ram
False
1
3
5
Datatypes and Its Typecasting
Here, I am using only primitive data types are as follows as:
In [67]: x=str(56)
print(type(x))
y=int(8.42)
print(type(y))
z=float(6)
print(type(z))
<class 'str'>
<class 'int'>
<class 'float'>
Out[46]: str
<class 'int'>
<class 'float'>
Here, you have to use int() function to typecast the input data. First of all you have
to pass input() function inside the int() function to get input in the form of integer
datatype same in case of float we use float() function and in case of string you do
not need to use any function. str() function is used to typecast any value in string
but not use for input() function.
In [ ]:
Slicing on String
As we know that, string is an alphabetic and alphanumeric words and their
combination enclosed with double qoutation marks. We can play with string with
the help of the slicing concept. Slicing is a concept of extracting sub-string from the
string just like there is a word Jupiter and i want to get sub-string from second
letter till fifth letter. For that we use the concept of slicing.
waga
wgnh
After writing the name of the string variable we use square bracket both first open
bracket and then close bracket. Between these two bracket we write the two
position first one is starting position and after colon the end position. If you use two
colon then after second colon you set number of steps it jumps. Here, the letter in
seventh position is excluded but the third position letter of the word is included.
Now, in third line I am using "2" as a step jumper so it jumps 2 step then print
letter. The rule of slicimg says that the given position before colon is included but
after colon the given position is excluded. If you not giving position at start then by
default it takes 0 as starting index and if you not given end position then it takes
last index of the string by default.
Scienti
tsitneicS
BramhaVishnu
BramhaVishnuMahesh
ASHOK CHAKRA
ashok chakra
1. upper() function is used in the name of the string variable then use dot
after that call the upper() function. It change the lowercase in the string
to uppercase and if string is in uppercase then it print uppercase with
no change.
2. lower() function is used on string to convert the uppercase letter in
string into lowercase letter but if the letter is in lowercase then it
remains same there is no change.
3. strip() function is used on string to remove white spaces at the starting
of the string and at the ending of the string.
4. replace() function is used on string to replace any targeted letter into
desired letter by passing both in the arguments of the replace()
function. In first argument we pass the targeted letter in second
argument we pass the desired letter.
Bramhos my favorite
[' Bramhos my favorite ']
Gramhos my favorite
Welcome!Amrit Keshari
In [ ]:
More on Booleans
Boolean is a type of datatype that contains only True and False values. When we
convert or typecast any value into boolean then we use bool() function. This bool()
function either return True or False after passing any value in the argument of
bool() function. If the bool() function returns True then the value which we pass in
the argument of bool() function is .truthy value. If the bool() function returns
False then the value which we pass in the argument is falsy value.
True
True
False
True
False
False
All the integer values, float values, string, list, tuple, dictionary, set values are
truthy values as when we pass these things in bool() function then it returns True
as an output. If we pass empty string, None, zero, empty list, empty turtle, empty
dictionary, empty set then it returns False as an output.
Types of Operators
72
24
1152
2.0
0
True
True
False
True
False
False
True
False
0
6
6
16
1
5. Identity Operator (is) operator is mainly used to check whether the left
operand is pertaining to object to the right operand. It just check two
operand if the object of both operand is same then it returns true
otherwise it returns false. (is not) operator is mainly used to check
whether the left operand is not pertaining to the right one then it
returns true. Simply means if both the values are equal then (is)
operator returns true.
True
True
In [ ]:
List
List is a sequential datatype that have ability to store multiple values in a single
variable. List is arranged in order that's why it is ordered. The elements of list have
their own index that's why it is indexed. We can add and remove elements in list
and we can replace value of the list elements that's why it is changeable. List
allows duplicates values because it find the elements by using index. List is in the
square brackets.
In [7]: #List
list1 = [2,4,1,5,5,1,2,6]
print(list1)
[2, 4, 1, 5, 5, 1, 2, 6]
7
1
[1, 3, 4, 6, 7]
[1, 4, 6, 7]
[1, 6, 7]
[]
1
2
3
4
5
6
7
2
3
4
5
6
7
8
Slicing in List
Slicing in List is the concept in which we separate a small part of list. Just like if list
have 11 elements then we extract 3rd to 7th element as part of the list. This is
called slicing in list. To extract a part of list from given list variable, we have to first
write the name of the list variable then open square bracket and write the index
from where you start fetching elements is called start, then write the index till
where you want to stop fetching data is called end. Note start is included but end
is excluded but before end all are included. Another thing is step that tell you how
much jump after first element to second element and second element to third
element it mean (n-1)th element to nth element how much gaps occur.
Between start and end there is one colon and between end and step there is
another colon.
You can also use negative indexing in slicing but in case of positive indexing we
start counting index from the start of the element in List and index start with zero
but in negative indexing index start with -1 and goes upto -n. One more thing is
that when we use negative indexing then we start counting index at the end of the
element in List. See the program here, I am using -1 as a step in the Tuple so it just
reverse the tuple as you see.
In [9]: y = amritList[-3:-9:-1]
print(y)
In [ ]:
Tuples
Tuples are the sequential datatype that stores multiple value in a single variable
just like list. But there is one difference between the list and tuple is that we can
make change in list but we cannot make change in tuple that's why tuple is
unchangeable. But one thing python allow in tuple is that we can unpack the
values of variable and extract it. Tuples are ordered because their each elements
have index number. Tuples are indexed as index for each element exist. Tuples
allow duplicate values. Tuple is always enclosed with small brackets. If you make a
tuple of one element only then you have to add one comma for that in the tuple
otherwise it throws error.
7
7
12
23
[34, 45, 56, 99]
2
3
5
6
7
11
23
34
94
22
33
44
99
Slicing in Tuples
Slicing in Tuple is the concept in which we separate a small part of tuple which you
can say sub-tuple. Just like if tuple have 10 elements then we extract 3rd to 7th
element as part of the tuple. This is called slicing in tuple. To extract a part of tuple
from given tuple, we have to first write the name of the tuple variable then open
square bracket and write the index from where you start fetching elements is
called start, then write the index till where you want to stop fetching data is called
end. Note start is included but end is excluded but before end all are included.
Another thing is step that tell you how much jump after first element to second
element and second element to third element it mean (n-1)th element to nth
element how much gaps occur. Between start and end there is one colon and
between end and step there is another colon.
In [7]: print(x)
(4, 5, 6, 7)
You can also use negative indexing in slicing but in case of positive indexing we
start counting index from the start of the element in Tuple and index start with zero
but in negative indexing index start with -1 and goes upto -n. One more thing is
that when we use negative indexing then we start counting index at the end of the
element in Tuple.
In [14]: y = amritTuple[-1:-7:-1]
print(y)
(11, 10, 9, 8, 7, 6)
Here, I am using -1 as a step in the Tuple so it just reverse the tuple as you see.
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Set
Set is a sequential datatype just like list and tuple. But it is just opposite to list as
list are ordered, indexed, changeable and allow duplicates but set is unordered,
unchangeable, unindexed and don’t allow duplicates.
Set is not ordered because their elements has no index and without index the
element cannot be in ordered form. Another thing set does not allow duplicate
values because it has no index for their element so it cannot distinguish between
duplicates if index exist then it distinguish two similar value by their index only.
In [6]: print(kSet)
{1, 2, 3, 4, 5}
Found
True
Computer
Coding
Technology
Science
In [3]: amritDict = {
"name":"Amrit",
"surname":"keshari",
"laptop":"dell",
"marks":8.6,
"books":2
}
print(amritDict)
In [30]: keshDict = {
"X":67,
"Y":76,
"Z":98
}
print(keshDict["Y"])
print([Link]())
print([Link]())
print([Link]())
76
dict_items([('X', 67), ('Y', 76), ('Z', 98)])
dict_values([67, 76, 98])
dict_keys(['X', 'Y', 'Z'])
In [46]: dictOfAmrit = {
"Trust":True,
"Books":2,
"Thinking":108,
"Battery":86,
"Name":"Amrit"
}
#For keys
for i in dictOfAmrit:
print(i)
#For values
for i in dictOfAmrit:
print(dictOfAmrit[i])
Trust
Books
Thinking
Battery
Name
True
2
108
86
Amrit
Opera
Google
Web
Coding
34
Gemini
Javascript
True
('Opera', 34)
('Google', 'Gemini')
('Web', 'Javascript')
('Coding', True)
If Statement
In case of using if statement we only check one condition only. if that one
condition is true then we perform some task otherwise nothing is happen. If
statement just check the condition that is passed in the if statement if it is true
then program runs only. First of all, we write the if keyword then write the condition
after that use colon then come to next line and use indentation before writing print
statement. Here, indentation is necessary below the ":" statements. Indentation
means one tab or four space.
In [5]: pendrive = 52
if(pendrive>50):
print("I use it")
I use it
Shorthand of if statement
TRUE
If-Else Statement
In case of using if-else statement we check single statement but now we execute
program when condition meets or condition return true but if condition does not
meet or condition become false then we execute another program for that or
printing some messages as you wish. First of all, we write the if keyword then write
the condition we want to check and then colon and then write program in next line
with indentation in the statement. After that go to next line and start with else
keyword and then colon after that go to next line an write program for else
statement with indentation.
TRUE
If-Elif-Else Statement
In case of using if-elif-else we check more than one condition and execute
different programs for different conditions just like if first condition is true then if
statement execute but if second or third condition is true then elif statement
execute and atlast if no one condition meets then the program of else statement
execute. First of all, we write if statement with condition then we write elif
keyword and then write condition after that write colon then in next line write the
program you want to execute when condition of elif statement returns true. The
more the condition, the more the elif block use.
Tablet
Shorthand of if-elif-else
TRUE_2
Match Statement
There is a very new concept in Python is Match Statement Concept which is just
familiar with Switch Case statement in other programming language like C, C++,
Java. Few years ago, there is no concept of switch case statement in python but
now it is possible due to match statement. Now, in match statement we can
check multiple conditions and perform code for multiple condition meet each. Here,
case statement (1-5) check whether match statement returning their values or not
just like here match statement return 5 then case with value 5 execute its code.
case _: this is a default case which we write in python like this.
In [41]: count = 5
match count:
case 1:
print("ONE")
case 2:
print("TWO")
case 3:
print("THREE")
case 4:
print("FOUR")
case 5:
print("FIVE")
case _:
print("Nothing!")
FIVE
To write while loop first of all, we have make an iterative variable i then in next line
we have to write while keyword and then we write the condition which we want to
check and then use colon after that in next line write the program and after
program write increament statement i=i+1 like this atlast.
0
1
2
3
4
5
6
7
8
9
10
We use break keyword in looping statement to stop the repetition of loop program
after meeting certain condition and hit break keyword. When the program hit
break keyword, the command or control goes outside the loop and loop stop
working. Let us see the example code given below:
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
We use else statement in while loop to execute the code when condition does not
meet our requirement. Suppose we execute a while loop when its condition returns
true then only it executes the program but when condition returns false then loop
stops instead of stoping loop we just want to send message that the condition is
failed so the loop end. For this we use else statement.
In [1]: #while using else
i = 0
while(i < 11):
print(i)
i = i + 1
else:
print("Loop End")
0
1
2
3
4
5
6
7
8
9
10
Loop End
0
1
2
3
4
5
6
7
8
9
10
You can also use single argument in the range() fnction and the single argument
value in range function is the end value of the loop. One more thing in range()
function the end value is excluded but before that is included in the loop.
By using break keyword in the for loop, break keyword is mainly used to remove
control out of the for loop when it hits the condition where break statement
present. It is mainly used to stop the loop.
0
1
2
3
By using continue keyword in the for loop, continue keyword only skip the loop
when condition met where continue statement present. Only for that contion the
loop is skipped but after that loop will continue running till for loop condition.
0
1
2
3
5
6
Else statement is mainly used in for loop to excute program or print message
when condition does not meet our requirements or it return false. This will print the
message that the loop is now going to end.
Here, we use for-each loop as a looping statement because just like list and tuple
not all the sequential datatypes are in ordered form or having index so it is too
difficult to print their values as it is unordered and unindexed. For that for-each
loop is used that visit each value once and throw them to i variable then that i
variable we print. This is how for-each loop works.
1
3
Amrit
5
6
Keshari
9
FIVE
Function is a line of code which is in the particular code block that starts with the
keyword named def then we write name of the function and then use parentheses
and after that ends with colon then goes to new line and write the program of the
task we want to do in our computer by using indentation. After colon in next line
first you have to take either four space or one tab then start writing program. By
this way, we can define the function in python. This indentation shows that your
code is in the code block of particular funtion and it runs only if when its particular
function is called.
In [9]: func()
To call or invoke the function, we just have to write the name of the function and
after that write the parentheses if function having some parameter then put values
into the argument and after that you should call or invoke but if the function having
no parameter then you do not need to pass any argument during the invoking or
calling a function.
Now see the calling or invoking of function with arguments and function without
arguments
Author:Aman Gupta
Author:Raj Agarwal
Author:Amrit
My friend is Aditya
How are you Aditya
My friend is Deepak
How are you Deepak
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[17], line 2
1 #function call with positional arguments
----> 2 amritFunction(8)
X:5 balls
Y:7 Bats
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[27], line 2
1 #function call with keyword arguments
----> 2 amritFunction(y=9)
See it prints all the values that we pass as an argument during function call. But
when it comes to print all the elements one by one using print function it print all
the elements and it can be possible using loop statements easily. Lets have a look.
1
2
3
4
5
6
7
1
2
3
Element:68
Element:Amrit
Element:Keshari
Element:True
Lambda in Function
Lambda is a concept in python to create an anonymous function. Lambda takes
multiple arguments but it takes only one expression to execute itself in the
program. As we know that lambda is anonymous function so we have to create a
variable and then assign lambda function on that variable so that the value as an
output which lambda yields is stored in that created variable.
To write lambda we use lambda keyword after that we write desired number of
arguments as variable then we use colon after colon we write an expression that
perform by taking these values of the argument. As lambda function is an
anonymous function so the variable where lambda function is assigned, when we
print that variable then we pass parameters on that variable as a function it means
we treat created variable as a function.
30
120
As you see that we can create more function with the same function. See here we
create plusFive() and plusTen() both of these function using single adder()
function. This is the way to use the lambda function as an anonymous function in
python.
In [ ]:
Recursion in Python
Recursion is the concept of function in which function call itself under base
condition to execute program repeatedly. There is two parts of the recursion are
base condition and recursive relation/function The base condition is a
condition when this base condition returns true then recusive function stop its
repeatation and recursion end. The another thing is recursive relation that shows
design of the recursive function means increment or decrement of values of
arguments in function or any operation with the argument of the recursive
function.
Amrit
Amrit
Amrit
Amrit
Amrit
This printing of names can be done by using loop statements but now we can do it
using recursion as recursion saves our time as compared to looping statements.
Therefore, I use recursion to print number of times my name. So, it is confirmed
that we can use recursion in place of looping statement. This is how recursion
takes place.
Here, we see that firstly amritNumber(7) comes in the stack then amritNumber(6),
then amritNumber(5), then amritNumber(4) till amritNumber(0). Now,
amritNumber(0) pop out from stack as it return something then
amritNumber(1)pop out, then amritNumber(2) pop out, then amritNumber(3) pop
out and it goes till amritNumber(7). This is how the stack is working like a stack in
the system.
7
6
5
4
3
2
1
Recursion is just working on the principle of LIFO Last In First Out. It is just working
like a stack.
copyright © 2025 By Amrit Keshari
In [ ]:
List Comprehension
List comprehension is the concept in which we use conditional statements and
looping statements inside the square bracket to create a list from the given list. It
means just like we have a list of natural numbers from 1 to 51 if you want to create
list of odd numbers and even numbers from the natural number list then you
have to use list comprehension concept. By list comprehension we can create
new list with specified data or values that is filtered from the previous list.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51]
Here, first of all we open square bracket then firstly write expression whatever if
you only want to store items in list then only write x as an expression but if you
want to double the elements after getting items from the loop then you use x*2 as
an expression. now after expression we use loop statements in single line
statement after that at last you use conditional statement to filter the items from
the list. Atlast we close the square bracket.
List Comprehension For Odd Numbers (With Conditional Statement & Looping
Statement)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41,
43, 45, 47, 49, 51]
Here, I am using for-each loop in program because we have already list so we fetch
all the items from the list. Then by using conditional statement we check all the
elements of that list and then it create a new list where it puts all the elements of
that list that satisfies the condition of even number whether it is divisible by two or
not. If it is not divisible by two then that element is put into the new list.
List Comprehension For Even Numbers (With Conditional Statement & Looping
Statement)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Now, using nested list comprehension we convert matrix (List of lists) into a
simpler list format. Here, in nested list comprehension we use double looping
statement instead of single looping statement that we use in list comprehension.
Now we are using double looping statement along with a conditional statement.
Here we use double looping statement because we work on List of list that is on
matrix so for working on matrix we need double looping statement the first
looping statement is used to extract all the list from the matrix and the second
looping statement is used to extract all the elements of the extracted list. Then we
can apply conditional statement after writing both of these looping statements.
The first looping statement is for ilist in listMatrix is used to extract all the lists
present in the matrix then we use second looping statement just after writing first
looping statement. The second looping statement is for x in ilist that is used to
extract all the elements from the present extracted list. Now the new list is formed
that contains only elements. Now atlast we use conditional statement that is if
x%2 == 0 that is used to filter all the elements as the element satisfies the
condition or not. If the element satisfies the condition then it is put into the new
formed list by nest list comprehension. This is how nested list comprehension
works.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[52], line 2
1 del amritList
----> 2 print(amritList)
Yes, it does not support item deletion of tuple but it support overall tuple deletion.
In [72]: print(amritTuple)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[72], line 1
----> 1 print(amritTuple)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[83], line 1
----> 1 del amritSet
2 print(amritSet)
As we know that dictionary and set both are unindexed as they have no index. So,
here i am not using del statement for deleting single element just like i do in list
and tuple as they are indexed.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[94], line 2
1 del amritDict
----> 2 print(amritDict)
In [ ]:
File Handling
File handling is a concept of programming in which we handle and manage the file
with the help of programming. Just like writing a python code that can create a new
file, delete a file and update a file. In python, file handling can be achieved by
importing os module in python program for deletion operation only.
Some of the function that is being used to handle and the operations happen on
files like creating a file, deleting a file and updating a file. These function takes
name of the file and mode of opening the file as an arguments of the function.
open(fileName,mode) is a function that is mainly used to open the file from the
system. open() function has two parameters the first parameter is for location of
the file and second parameter is for mode of opening a file. Here, in file handling in
python we use with statement because using with statement handlesclosing the
file after operation done on the files automatically as we do not need to write
close() function for closing files.
Here, r refers to open the file in reading mode and t refers to the operation is in for
text mode.
Some modes of opening a file in file handling concept of python are as follows as:
1. r mode open the file for reading operation in the file, but if file does not
exist in your system then it throws error. So this mode is applicable only
if the file exists in your computer system.
2. a mode open the file for updating operation means to append some
data in the file. If file does not exist in your computer system then this
mode helps you to create a new file in the computer system and then
append the data in that new file. It will start adding content at the end
of the file means it will not overwrite the content of the file.
3. w mode open the file for writing operation in the file, but if file does not
exist in your computer system then it will create a new file in your
computer system and then start writing data in the new file. It will
overwrite the whole content of the file.
4. x mode is used to creation of file if the file you create exist in the
computer system then it throws error.
5. b mode is mainly used to do operation in binary mode.
6. t mode is mainly used to do operation in text mode.
Reading File Using File Handling
In [ ]: amritFile = open("C:/Users/AMRIT%20KESHARI/Downloads/Basic_Python1.pdf", "rt")
print([Link]())
[Link]()
Here, read() function in file handling in python use to read the files which is
present in the amritFile variable. If you are not using with statement then you
have to close the file using close() function.
As we know that, read() function is used to read file. The read() function will print
the whole text but if you want to print desired number of text then you can do it.
As read() function have a parameter where you pass number of words you want to
print as an argument.
By using readLine() function we can print one line of the file, but if you want to
print two or more lines of file then you have to use n times of readLine() function
for printing n lines from the file. As we know that the readLine() function returns
the single line from the file.
For reading the whole file, we use looping statement just like for-each loop for
reading whole file. First of all we open the file using with statement and open()
function then we use for-each loop to traverse all the content of the file and then
print it.
In [ ]: with open("C:/Users/AMRIT%20KESHARI/Basic_Python1.pdf", "r") as amritFile:
for i in amritFile:
print(i)
First of all, we use with statement and invoke open() function to open file with write
mode for that we use w as a file mode. If you want to only insert the text without
overwriting the file content then you have to use a append mode instead of w
write mode. Then we use the file variable and after writing file variable use dot
then invoke write() function. In write function, we have one parameter where we
pass the string or text that i want to insert in the file. So, write the string or text in
the parentheses of write() function.
Append (It will end this content at the end of the file)
In [ ]: import os
[Link]("C:/Users/AMRIT%20KESHARI/Basic_Python1.pdf")
In [ ]: import os
if [Link]("C:/Users/AMRIT%20KESHARI/Basic_Python1.pdf"):
[Link]("C:/Users/AMRIT%20KESHARI/Basic_Python1.pdf")
else:
print("File not Exists")
In [ ]: import os
[Link]("C:/Users/AMRIT%20KESHARI/Desktop")
In [ ]:
In [ ]:
Class & Object in Python
Class is a user-defined datatype which has both variables and methods bounded
with each other and is used to bound data and methods together. Class is written
by using class keyword in python. First of all, we write the keyword class then we
write name of the class after that we use colon and then go to next line. In next
line, follow rule of indentation and then write the variables and functions in that
class code block. In class, variables are called properties or attributes of our class
and functions are called behaviours of our class. Class is just like a map or
template to design an object in your python program. Just you want make your own
house for that you need to draw a map of your house. That map of your house is
like a class and your made house is just like an object. That's why class is called
logical entity whereas object is called physical entity. Each objects have their own
unique attributes or data so during each object call you will see change of
behaviour of the same method by changing objects.
Class Creation
Method is a block of code inside the class that is defined just like a function but
function is a block of code that is not present inside any class it is in the program
only. To call a Method, you need object name then dot and then call your method,
but in case of function you can call it directly by function name. Method can only
access object variables and each object has their own variables, but functions
access the data which you pass in the argument of the function in the parentheses
of the function. Method pass its object inside itself in its parentheses as a self
whereas function only pass variables in its parentheses.
Object Creation
When you create object then memery is allocated for each objects you create. As
class only define the structure but object hold the data and functions according to
the class defined. Objects are created when we call the class name just like calling
a function. See in the program given below.
Amrit:1
Amrit:True
Amrit:p
Amrit:sam
Amrit:9.05
Self Keyword
self keyword is used to show or it indicates the present instance or object of the
method when any method of the class is called. Let us see how self keyword
works. Our python program calls the function by first calling a class then call its
method after that it passes the object in the argument of the method of the class.
That passing of argument where present object is passed is considered in our
program as self. Actually intrepreter of python intreprete this program like ths but
we write the same thing just by calling object and the method only but behind the
computer it works like calling a class then mehod and then pass object in the
method.
In [40]: [Link](obj1)
[Link](obj2)
[Link](obj3)
[Link](obj4)
[Link](obj5)
Data
Data
Data
Data
Data
But in reality to code to create an object then call its method for that we just have
to first create an object.
Amrit:2
Now we will call the method of the object for that we use first name of the object
then dot after that name of the method. That's how we call the method of the
class.
In [59]: [Link]()
Data
Now we can also access the data and variables of the class just by using object
name and the dot and the name of the variables or attribute.
In [64]: [Link]
Out[64]: 8
First of all we define the class and its variable and methods inside the class scope.
Let us see in the program given below. Note that follow the rule of indentation
during class definition because you are going to create methods and methods
comes inside the class code block. So all the methods should be inside the class
code block named AmritCalc.
When we use variable f and s then we have to use self followed by dot.
Now we access the methods of the class by using object. For that first of all we
have to create object. When we create object then f and s variable is formed due to
constructor method. So for creating an object we have to call class name as a
function.
Now we have to access the method of calcObject method for that we call the
method by using object and dot. Lets see in the program given below.
In [137… [Link]()
Add: 6
In [139… [Link]()
Sub: -3
In [141… [Link]()
Mul: 54
In [143… [Link]()
Quo: 0.6666666666666666
In [145… [Link]()
Rem: 6
In [ ]:
In [ ]:
In [ ]:
In [ ]:
_ _ init _ _(self) Method
_ _ init _ _(self) method is a constructor method which is present inside the class
code block and it is the first defined method in the class code block. _ _ init _
_(self) method is mainly use to initialize the value to the object which you create
with the help of class. So see how we assign values to the class in the given
program. Also remember before writing _ _ init _ _ you have to write the keyword
named def and after writing _ _ init _ _ you have to give parentheses and pass the
self as an parameter of the constructor method.
Create a class and define _ _ init _ _ (self) in the class and then create a method
in the class to access the variable of the object. Here, self.a = a is mainly used to
assign the value to the object of the class. This will assign the value of a which
taken from the argument is assigned to the object variable.
Create an object to access the variable of the object. That variable is assigned in
the object. It can be accessed by calling the method through object.
In [21]: [Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[21], line 1
----> 1 [Link]()
As we see that we got an error. Do you know why this error comes? It comes
because when we access that variable inside the method then we are not using
self and as we know that the variable a is a object variable not a local if it is local
variable then we use only a but if it is an object variable then we have to self
keyword followed by dot before the name of the variable. Here, the error says that
a is not defined.
Here is the corrected code
In [37]: [Link]()
value of a:5
Suppose create a code of calculator using python and you want to greet your user
when they start using your code. For that you want to print Hello User Your Most
Welcome or Intruction before using your code for users just like for Addition
press 1 and for Multiplication press 2 like this. Then you need a constructor method
of class.
Welcome Sir!
1 for Addition
2 for Substraction
3 for Multiplication
4 for Quotient
5 for Remainder
Now the question is How many times the constructor is called when we call
different methods of the same class?
The number of times you use the object it means you will call the function by first
calling the object of the class. Just See in the program given below.
Constructer is called
Constructer is called
In [73]: [Link]()
[Link]()
Hello Guys!
Hello Guys!
Constructer is called
Constructer is called
Hello Guys!
Hello Guys!
You will see that constructor is called two times because we made it two times.
When object is created a memory is allocated for the object. But you where the
memory is allocated for the object? The memory for the object is allocated in the
heap memory. All the objects you create from the class is allocated in the heap
memory of the computer system. That heap memory provide address to the
objects you create during object creation.
Amrit Keshari
In [84]: object2 = Amrit()
Amrit Keshari
Now we are going to see the address of both of these object we create now. Every
time we create an object, a new object is created in the heap memory. Every time
when you execute a new memory is allocated.
In [87]: print(id(object1))
2270311708480
In [96]: print(id(object1))
print(id(object2))
2270311708480
2270340870128
The memory is allocated to the object randomly not in an arranged way in the
heap memory.
Now, both of these two objects are created. Here, when we call the class as a
function during object creation. Then we pass only two arguments are 12 and 91 in
the object1 and 56 and 23 in the object2. But our program is explicitly or
bydefault pass the present object as third argument in place of the self keyword.
No
Now, I change the value of the variable a of the object1
In [118… object1.a = 56
Yes
Here, the compare() method is defined in the class that check whether the data of
two objects is equals or not. Here, in compare(self) in place of the self the object
that uses this compare(self) function is passed then the object from whom to
compare is passed in the place of newObj.
In [151… if [Link](objectOf2):
print("Yes")
else:
print("No")
No
In [156… objectOf1.a = 66
Yes
Now we compare the value of b of objectOf1 with the value of b of objectOf2
No
In [194… [Link]()
This update() method will update the value of b in the object and assigned it to
the variable of the object.
Yes
Empty Class
To create an empty class you just have to write pass keyword inside the class code
block by following the rule of indentation.
This is the simple program of the empty class. Empty class also have their objects.
And their objects also present in the heap memory. In python all are like int, float
are objects. See the proof of object of the empty class in the given program.
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Varibles & Methods in OOPS
Types of Variables in OOPS
There are variables which we use in our class during class definition. There are
mainly two types of variables in the class are as follows as based upon the place
where they defined:
In [16]: print([Link])
print([Link])
print([Link])
4
4
4
The value of leg variable of all the objects we create from the same class is same
and when we change the class variable named leg then the value of leg variable
changes for all the objects formed from the same class.
To change the value of the class variable named leg we have to first write the
name of the class then use dot then write the name of the class variable and use
assignment operator named equals to (=) then assign value.
In [21]: [Link] = 7
In [23]: print([Link])
print([Link])
print([Link])
7
7
7
Now, the value changes for all the objects we create from the same class.
See we have assigned different values to the variable of the different objects. To
access the object variables, we have to write the name of the object followed by
dot then write name of the method to access the value of the different objects of
the same class.
In [33]: print([Link])
print([Link])
print([Link])
Red
Green
Yellow
As you have seen that different objects have different values. This is how instance
variable look like.
There are some functions which we use during class definitions are called methods.
There are mainly three types of methods in class in python are class method,
instance method and static method. Here, class method and static method both
are different but in case of the variable class variables and static variables both are
same.
If you are not using the decorator named @classmethod , then you will get error.
So, you have to use @classmethod decorator before defining the class method.
In [66]: [Link]()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[66], line 1
----> 1 [Link]()
We do not need to create object to access the class method because it pertains to
the class.
In [57]: [Link]()
Name:Amrit
Instance method is of two types are Accessor methods and Mutator Methods are as
follows as:
34
2. Mutator Methods are the types of instance method that change the
present value of the instance variable. Just like each object carry its
own value of its variable. So, if you want to change its value you just
need to use the instance method named Mutator Method.
In [83]: [Link](11)
In [85]: object.x
Out[85]: 11
If you are not using the decorator named @staticmethod, then you will not get any
error now but in past you got error.
Hello Indians!
In [116… [Link]()
Hello Indians!
In [ ]:
In [ ]:
In [ ]:
In [ ]:
-RRIV'PEWW'SRGITX
8LIGSRGITXSJMRRIVGPEWWGSRGITXMWEQIXLSHSPSK]SJSFNIGXSVMIRXIHTVSKVEQQMRKMR[LMGL[I
GPEWWREQIH'7)MR[LMGL[IGERHI«RIWYFGPEWWPMOI%VXM«GEP-RXIPPMKIRGI1EGLMRI0IEVRMRKERH
(EXE7GMIRGI%JXIVHI«RMRKMRRIVGPEWWMRWMHIXLISYXIVGPEWW]SYLEZIXSQEOIobject of inner
(YVMRKSFNIGXGVIEXMSRSJinner class[IRIIHXS«VWX[VMXIREQISJXLISYXIVGPEWWXLIRHSXEJXIV
XLEX[ILEZIXSGEPPMRRIVGPEWWNYWXPMOIEJYRGXMSR7IIMRXLITVSKVEQ"[Link] = [Link]()
class CSE:
def __init__(self):
[Link] = 18
[Link] = [Link]()
def printSum(self):
print(f"Outer:{[Link]}")
[Link]()
class ai:
def __init__(self):
self.x = 12
def display(self):
print(f"Inner:{self.x}")
objCSE = CSE()
[Link]()
Outer:18
Inner:12
=SYGERQEOIELMIVEVGL]SJGPEWWIWF]YWMRKXLIGSRGITXSJMRRIVGPEWWMRT]XLSR7IIMRXLI
TVSKVEQKMZIRFIPS[EVIEWJSPPS[WEW
class Grand:
def __init__(self):
[Link] = 85
[Link] = [Link]()
[Link] = [Link]()
def display(self):
print(f"Grand:{[Link]}")
[Link]()
[Link]()
class Paternal:
def __init__(self):
[Link] = 45
[Link] = [Link]()
def dispfst(self):
print(f"Paternal:{[Link]}")
[Link]()
class Son:
def __init__(self):
[Link] = 17
def printBoy(self):
print(f"Son:{[Link]}")
class Maternal:
def __init__(self):
[Link] = 39
[Link] = [Link]()
def dispscd(self):
print(f"Maternal:{[Link]}")
[Link]()
class Daughter:
def __init__(self):
[Link] = 15
def printGirl(self):
print(f"Daughter:{[Link]}")
objGrand = Grand()
[Link]()
Grand:85
Paternal:45
Son:17
Maternal:39
Daughter:15
,IVI[ILEZIWIIRXLEXMJ]SYLEZISYXIVGPEWWXLIRMRRIVGPEWWXLIRMRRIVMRRIVGPEWW(YVMRK
SFNIGXGVIEXMSRSJMRRIVQSWXGPEWW]SYLEZIXS«VWX[VMXISYXIVQSWXGPEWWXLIRHSXXLIRSYXIVGPEWW
XLIRHSXXLIRMRRIVGPEWW8LMWMWORS[REWLMIVEVGLMGEP[E]XSHI«RIERSFNIGXNYWXPMOI"[Link]
= [Link]()
-RLIVMXERGIMWXLITVSTIVX]SJSFNIGXSVMIRXIHTVSKVEQQMRKMR[LMGL[IMRLIVMXSRIGPEWWXSERSXLIV
WSXLEX[IGEREGGIWWXLIEXXVMFYXIWERHQIXLSHWSRIGPEWWXSERSXLIVGPEWW8LEXMWEGPEWWMW
MRLIVMXIH[MXLERSXLIVGPEWWXLIRXLIEXXVMFYXIWERHFILEZMSVWSJERMRLIVMXIHGPEWWGERFIIEWMP]
EGGIWWMFPI[MXLXLILIPTSJGLMPHGPEWWSVWYFGPEWWJVSQ[LMGLEPPGPEWWIWEVIMRLIVMXIH
Note:
Single InheritanceMWEX]TISJMRLIVMXERGIMR[LMGL[IMRLIVMXSRP]SRIGPEWW8SEGLMIZIXLMW
MRLIVMXERGI[IRIIHX[SGPEWWIWXLI«VWXSRIGPEWWMWTEVIRXGPEWWSVWYTIVGPEWWERH
ERSXLIVSRIGPEWWMWGLMPHGPEWWSVWYFGPEWW,IVIXLIGLMPHGPEWWGEREGGIWWXLIEXXVMFYXIW
ERHQIXLSHWSJXLITEVIRXGPEWW*MVWXSJEPP[ILEZIXS[VMXIXLIREQISJXLIderived class
XLIRSTIRXLITEVIRXLIWIWERH[VMXIXLIREQISJXLISRIFEWIGPEWW SRP]SRIGPEWW[LMGL
]SY[ERXXSMRLIVMX ERHXLIRGPSWIXLITEVIRXLIWIWERHXLIR[VMXIXLIGSPSR%JXIVXLEXF]
JSPPS[MRKXLIVYPIWSJMRHIRXEXMSRHI«RIXLIEXXVMFYXIWERHQIXLSHWMRWMHIXLIHIVMZIHGPEWW
Here is the program for the single inheritance. Please have a look at the program given below
class Father:
def talent1(self):
print("Talent1 of Father")
def skill1(self):
print("Skill1 of Father")
class Daughter(Father):
def talent2(self):
print("Talent2 of Daughter")
def skill2(self):
print("Skill2 of Daughter")
2S[[IGVIEXIXLISFNIGXSJchild classXSEGGIWWXLIFSXLXLIWOMPPWERHXEPIRXWSJ*EXLIVERH
(EYKLXIV
childClassObject = Daughter()
2S[EGGIWWEPPXLIQIXLSHWSJFSXLXLIGPEWWYWMRKXLIWYFGPEWWSVHIVMZIHGPEWWSFNIGX
childClassObject.skill1()
Skill1 of Father
childClassObject.skill2()
Skill2 of Daughter
childClassObject.talent1()
Talent1 of Father
childClassObject.talent2()
Talent2 of Daughter
Multiple InheritanceMWEX]TISJMRLIVMXERGIMR[LMGL[IMRLIVMXQSVIXLERSRIGPEWWMRXLI
HIVMZIHGPEWWSVGLMPHGPEWWWSXLEXMXGEREGGIWWXLIEXXVMFYXIWERHQIXLSHWSJQSVIXLER
SRIGPEWWIWXLEXMWQYPXMTPIGPEWWIW*MVWXSJEPP[ILEZIXS[VMXIXLIREQISJXLIderived
classXLIRSTIRXLITEVIRXLIWIWERH[VMXIXLIREQISJXLIFEWIGPEWWIW XLIGPEWWIW[LMGL
]SY[ERXXSMRLIVMX WITEVEXIIEGLGPEWW[MXLGSQQEERHXLIRGPSWIXLITEVIRXLIWIWERH
XLIR[VMXIXLIGSPSR%JXIVXLEXF]JSPPS[MRKXLIVYPIWSJMRHIRXEXMSRHI«RIXLIEXXVMFYXIWERH
QIXLSHWMRWMHIXLIHIVMZIHGPEWW
class Base1:
def method1(self):
print("Method 1 is calling")
class Base2:
def method2(self):
print("Method 2 is calling")
class Base3:
def method3(self):
print("Method 3 is calling")
,IVI[IEVIKSMRKXSMRLIVMXEPPXLIFEWIGPEWWIWMRXLIHIVMZIHGPEWW
the base classes as all the base classes inherit from the derived class.
objectDerived = Derived()
Now, we access all the methods of both base classes and derived class by using object of derived
class.
objectDerived.method1()
Method 1 is calling
objectDerived.method2()
Method 2 is calling
objectDerived.method3()
Method 3 is calling
objectDerived.method4()
Method 4 is calling
the FEWIGPEWW and then inherit the WIGSRHHIVMZIHGPEWW from the «VWXHIVMZIHGPEWW then
inherit the XLMVHHIVMZIHGPEWW from the WIGSRHHIVMZIHGPEWW till last derived class we do
inheritance like this. This process make a chain of levels of inheritance. Here, classes inherit
from the class that is already inherit from another class which forms a hierarchical chain in
inheritance.
class A:
def behaviour1(self):
print("A behaviour is calling")
class B(A):
def behaviour2(self):
print("B behaviour is calling")
class C(B):
def behaviour3(self):
print("C behaviour is calling")
Now, for accessing all the methods of all the classes we need to call the object of lastly derived
class.
objectLastDerived = C()
Now, with the help of the object of lastly derived class we can easily access all the methods of all
the base classes that derived from other class and base class.
objectLastDerived.behaviour1()
A behaviour is calling
objectLastDerived.behaviour2()
B behaviour is calling
objectLastDerived.behaviour3()
C behaviour is calling
4. Hierarchical Inheritance is a type of inheritance in which we inherit all the derived class with
the same base class. Here, all the derived classes inherit the attributes and methods of the
single base class. Just like your parents have four childs then all four childs has taken some
class Parent:
def parentFeature(self):
print("Good Looking")
class Son(Parent):
def sonFeature(self):
print("Intelligent")
class Daughter(Parent):
def daughterFeature(self):
print("Cuteness")
Here, to achieve inheritance we need to create object of n-1 number of classes where n is the
number of total class used in inheritance and why n-1 because there is one base class whose
object is not created to achieve inheritance. Or we can say total numbers of derived class.
objectSon = Son()
[Link]()
[Link]()
Good Looking
Intelligent
We need to create object of the class Daughter as it is also inherited with the Parent class.
objectDaughter = Daughter()
[Link]()
[Link]()
Good Looking
Cuteness
5. Hybrid Inheritance is a type of inheritance in which we combine more than one inheritance.
Just combining multilevel inheritance and multiple inheritance. To combine any two or more
types of inheritance is known as hybrid inheritance it means to make hybrid of different types
of inheritance.
class A:
def call_A(self):
print("A is calling")
class D:
def call_D(self):
print("D is calling")
class E:
def call_E(self):
print("E is calling")
class B(A) :
def call_B(self):
print("B is calling")
Multiple InheritanceSJGPEWW'XSGPEWW&GPEWW(GPEWW)
class C(B,D,E):
def call_C(self):
print("C is calling")
objectB = B()
objectB.call_A()
objectB.call_B()
A is calling
B is calling
objectC = C()
objectC.call_B()
objectC.call_D()
objectC.call_E()
B is calling
D is calling
E is calling
'SRWXVYGXSVMR-RLIVMXERGI
;IYWIGSRWXVYGXSVMRXLIGPEWWJSVHI«RMRKZEPYIWSVEWWMKRMRKZEPYIWXSXLIZEVMEFPIW,IVIMJ[I
YWIGSRWXVYGXSVMRMRLIVMXERGIXLIR[LEXLETTIRWWII7YTTSWI]SYGVIEXIETVSKVEQSJWMQTPI
MRLIVMXERGI[LIVI]SYMRLIVMXERGIEGLMPHGPEWW[MXLETEVIRXGPEWW8LIRXLMROEFSYXMX[LMGL
GSRWXVYGXSV[MPPVYR«VWX[LIR]SYGVIEXIERSFNIGXSJGLMPHGPEWWSVHIVMZIHGPEWW
class Parent:
def __init__(self):
print("Parent init is calling.....")
class Child(Parent) :
def __init__(self):
print("Child init is calling.....")
8SGEPPXLIMRMXQIXLSH[ILEZIXSGVIEXISFNIGXXLIRMRMXQIXLSH[MPPFIEYXSQEXMGEPP]GEPPIH
objectChild = Child()
2S[MJ]SY[ERXXSGEPPXLIinitQIXLSHSJParent ClassXLIR]SYLEZIXSYWIXLIsuper()ERHXLIR
HSXERHXLIRER]QIXLSHSJXLITEVIRXGPEWW[LIXLIVMXMWinitQIXLSHSVER]SXLIVQIXLSHRS
QEXXIV
class Parent:
def __init__(self):
print("Parent init is calling.....")
class Child(Parent) :
def __init__(self):
super().__init()
print("Child init is calling.....")
VYRMX WinitQIXLSH[LIVIMXKSIWXS«VWXPMRISJGSHIFPSGOSJinitQIXLSHERHWIIXLEXsuper()MW
YWIHXLIRsuper()MWI\IGYXIHXLEXGEPPWXLIinitQIXLSHSJParent Class%JXIVGEPPMRKinitQIXLSH
JYRGXMSRSJXLIinitQIXLSH
2S[MRGEWISJQYPXMTPIMRLIVMXERGIXLIVIEVIQSVIXLERSRIParent ClassMRXLITVSKVEQ8LIR[MPP
MXGEPPEPPXLIinitQIXLSHSJEPPXLIGPEWWIWSVSRP]GEPPXLIinitQIXLSHSJ«VWXTEVIRXGPEWW7IIMR
XLITVSKVEQ[LEXLETTIRW#
class Mother:
def __init__(self):
print("Mother init is calling.....")
class Father:
def __init__(self):
print("Father init is calling.....")
2S[[IGEPPXLISFNIGXSJGPEWW'LMPHXLIRMX[MPPI\IGYXIXLIinitQIXLSHSJGPEWW'LMPH«VWXXLIRMX
I\IGYXIXLIinitQIXLSHSJGPEWW1SXLIVSRP]FYXRSXGEPPXLIinitQIXLSHSJ*EXLIVGPEWWMXMW
-RWLSVX1IXLSH6IWSPYXMSR3VHIVGERFIGEPPIHEW1631IXLSH6IWSPYXMSR3VHIVMWXLIGSRGITXMR
[LMGLMXMWSVHIV[LIVIT]XLSRWIEVGLJSVEQIXLSHMRELMIVEVGL]SJGPEWWIWMRQYPXMTPIMRLIVMXERGI
[LIRMXLMXWQYPXMTPIGPEWWIWMRQYPXMTPIMRLIVMXERGI[MXLXLIWMQMPEVREQISJXLIQIXLSH
in parentheses[LIVI]SYTEWWQYPXMTPIGPEWWIWERHTVMSVMXM^IXLIPIJXSRIGPEWWSJXLIQYPXMTPI
MRLIVMXERGI[LIVIXLIWMQMPEVQIXLSHMWTVIWIRXMJRSXTVIWIRXXLIRMXKSIWXSXLIWIGSRHPIJXGPEWW
ERHXLIRGLIGOXLIWMQMPEVQIXLSHREQIMJI\MWXXLIRI\IGYXIXLIWMQMPEVQIXLSH]SYGEPPEJXIV
WYTIV
,IVI[LIRXLISFNIGXSJ'LMPHGPEWWMWGEPPIHXLIRinitQIXLSHMWGEPPIHEYXSQEXMGEPP]EJXIVSFNIGX
GVIEXMSR;LIRinitQIXLSHSJ'LMPHGPEWWMWGEPPIHXLIRMXLMXWXLI«VWXPMRISJGSHISJXLIGSHI
FPSGOSJinitQIXLSHERHLMXWXLIsuper()XLIRGEPPinitQIXLSH8LMWPMRISJGSHI«VWXWIEVGLXLIinit
QIXLSHF]JSPPS[MRKXLI1IXLSH6IWSPYXMSR3VHIVERHEW[IORS[XLEXXLI1IXLSH6IWSPYXMSR
3VHIVWIPIGXXLIQIXLSHSRP]MJMX WMWMRXLIPIJXWMHIHGPEWWERHLEZMRKXLEXWMQMPEVQIXLSH[LMGL
[IGEPP[MXLXLIWYTIV -JRSSRIPIJXGPEWWLEZMRKXLEXWMQMPEVQIXLSHXLIRXLIQIXLSHSJVIWX
GPEWW[LIVIXLIWMQMPEVQIXLSHMWTVIWIRXMWGEPPIH
objectChild = Child()
4SP]QSVTLMWQ[SVHQEOIW[MXLXLILIPTSJPoly[LMGLQIERWQER]ERHmorphQIERWJSVQW
,IVIXLI[SVHTSP]QSVTLMWQQIERWSRIXLMRKGERQEOIQYPXMTPIJSVQW.YWXPMOIXLIWSYRHSJEPP
XLIERMQEPWEVIHMJJIVIRXPMOIXLIWSYRHGS[MWHMJJIVIRXERHXLIWSYRHSJHSKMWHMJJIVIRX&YXFSXL
EVIXLIWSYRHSJERMQEPW
(YGO8]TMRK
Duck TypingMWXLIX]TISJTSP]QSVTLMWQQIXLSHSPSK]SVETVSKVEQQMRKWX]PI[LIVIMXMWJSGYWIH
SRQIXLSHSJSFNIGXVEXLIVXLERXLIWTIGM«GX]TISJXLISFNIGXDuck TypingJSPPS[WXLIVYPISJ-JMX
W[MQWPMOIEHYGOERHUYEGOWPMOIEHYGOXLIRMXMWGEPPIHHYGOF]XLMWTVMRGMTPIT]XLSRGLIGOWMJ
SFNIGXLEWER]VIUYMVIHQIXLSHXSGSQTPIXIRIIHIHSTIVEXMSRSVRSXVEXLIVXLERXLIWTIGM«GX]TI
SJXLISFNIGXDuck TypingEPPS[HMJJIVIRXX]TIWSJSFNIGXWXSKMZIVIWTSRWIXSXLIWEQIQIXLSH
GEPPSVMRZSOIF]XLIMVS[R[E][LMGLIRLERGIGSHIVIYWEFMPX]
class Bird:
def sound(self):
print("Chirping")
class Reptile:
def sound(self):
print("Hissing")
class GenSound:
def __init__(self, obj):
print([Link]())
;IGERXLISFNIGXWSJFSXLXLIGPEWWIW[LIXLIVMXMW&MVHSV6ITXMPIRSQEXXIVFIGEYWIFSXLSJXLIQ
LEZIQIXLSHREQIHsound()
objBird = Bird()
objReptile = Reptile()
2S[[IGVIEXIXLISFNIGXSJGenSoundGPEWWERHEGGIWWXLIsound()QIXLSH
objGenSound = GenSound(objBird)
Chirping
None
objGenSound = GenSound(objReptile)
Hissing
None
8LMWMWLS[HYGOX]TMRKMW[SVOMRKPMOIETSP]QSVTLMWQMR4]XLSR
3TIVEXSV3ZIVPSEHMRK
3TIVEXSVSZIVPSEHMRKMWXLIGSRGITXMR[LMGL[ISZIVPSEHXLISTIVEXSVXSHSWSQIHIWMVIH
STIVEXMSR[I[ERX.YWXPMOIXLIEHHMXMSRSTIVEXSVMWQEMRP]YWIHXSEHHMRXIKIVW¬SEXWHSYFPIW
WXVMRKWFYXMXGERRSXEHHSFNIGXWSJXLIGPEWW&YXMXGERFITSWWMFPI[MXLXLILIPTSJSTIVEXSV
SZIVPSEHMRK
&IJSVIYRHIVWXERHMRKXLISTIVEXSVSZIVPSEHMRK[ILEZIXSYRHIVWXERHLS[STIVEXSVW[SVOFILMRH
XLIWGIRISJXLIGSHI%GXYEPP][LIR]SY[VMXIGSHIJSVEHHMXMSR
a = 56
b = 96
print(a + b)
152
&ILMRHXLIWGIRISJXLIGSHIQIERWGSQTMPIVGSRZIVXa + bMRXSXLIKMZIRGSHI
a. __add__(b)
152
MRXLITVSKVEQKMZIRFIPS[
class Total:
def __init__(self, mark1, mark2):
self.mark1 = mark1
self.mark2 = mark2
def __add__(self, obj):
c1 = self.mark1 + obj.mark1
c2 = self.mark2 + obj.mark2
c3 = Total(c1, c2)
return c3
,IVIMRXLIGPEWW[IVIHI«RISVSZIVVMHIXLI_ _ add _ _()QIXLSHWSXLEXMX[SVOWJSVXLIMVSFNIGXW
obj1 = Total(19,17)
obj2 = Total(12,15)
obj3 = obj1 + obj2
print(obj3.mark1)
print(obj3.mark2)
31
32
[ISRP]LEZIXSSZIVVMHIXLIWIQIXLSHWF]SYVS[R[E]XSEGLMIZIHIWMVIHSTIVEXMSRWSRHIWMVIH
HEXEX]TIW.YWXPMOIEHHQIXLSH[ILEZIEPPXLIQEKMGQIXLSHWJSVEPPXLISTIVEXSVW7SMJ]SY
RIIHXSSZIVPSEHER]STIVEXSV]SYNYWXLEZIXSSZIVPSEHMX WQEKMGJYRGXMSR8LISTIVEXSV[MPPFI
SZIVPSEHIHIEWMP
-J]SY[ERXXSWIIXLISTIVEXSVSZIVPSEHMRK[MXLERSXLIVSTIVEXSVNYWXPMOISTIVEXSVSZIVPSEHMRKSJ
GSQTEVMWSRSTIVEXSVSVVIPEXMSREPSTIVEXSV=SYSRP]LEZIXSSZIVVMHIXLImagic methodSJ
VIPEXMSREPSTIVEXSV7IIMRXLITVSKVEQKMZIRFIPS[
class Compare:
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, obj):
c1 = self.x + self.y
c2 = obj.x + obj.y
if c1 < c2:
return True
else:
return False
,IVI[IGLSSWI<PIWWXLERVIPEXMSREPSTIVEXSVXSSZIVPSEHMXWSXLEXMX[SVOJSVSFNIGXEPWS*SVXLEX
-EQSZIVVMHMRKXLIQEKMGQIXLSHSJPIWWXLERVIPEXMSREPSTIVEXSVXLEXMW_ _ lt _ _()QEKMGQIXLSH
obj1 = Compare(43,96)
obj2 = Compare(57,89)
Obj1 is losser
Suppose if you want to print the object then you pass object as an argument inside the print
function. Then print function will print its address. But we need content of the object for that we
print(obj1)
As we see when we print object of the class then it prints it's address and we need content.
class ObjShow:
def __init__(self, x):
self.x = x
def __str__(self):
return f"{self.x}"
Now, we have overrided the _ _ str _ _(). Let us create an object of the ObjShow class.
object = ObjShow(5)
print(object)
Method Overloading
Method Overloading is not possible in python because python does not support same name of the
function with different parameters. And as we know that method overloading is the concept of
class OOPS:
def __init__(self, x, y):
self.x = x
self.y = y
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def sum(self, x, y):
print(x+y)
def sum(self, x, y, z):
print(x+y+z)
obj1 = OOPS(4,5)
[Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-19-04840865e53b> in <cell line: 0>()
----> 1 obj1 = OOPS(4,5)
2 [Link]()
Next steps
: Explain error
obj2 = OOPS(4,6,9)
[Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-18-a1e128e61ac7> in <cell line: 0>()
----> 1 obj2 = OOPS(4,6,9)
2 [Link]()
Next steps
: Explain error
Method Overloading in Python can be achieved by using keyword arguments. See in the program
given below.
class Add:
def sum(self, x=None, y=None, z=None):
if x!=None and y!=None and z!=None:
print(f"Sum: {x+y+z}")
elif x!=None and y!=None:
print(f"Sum: {x+y}")
else:
print(f"Sum:{x}")
2S[[IGVIEXIERSFNIGXERHXLIREGGIWWMX Wsum()QIXLSHYWMRKXLISFNIGXF]JSPPS[MRKHSX
obj = Add()
[Link](8)
[Link](8,9)
[Link](5,8,9)
Sum:8
Sum: 17
Sum: 22
&]XLMW[E]]SYGEREGLMIZIQIXLSHSZIVPSEHMRKSJGLERKMRKSJRYQFIVSJTEVEQIXIVW
1IXLSH3ZIVVMHMRK
Method OverridingMWXLIGSRGITXSJ3347MR[LMGLEQIXLSHSJTEVIRXMWMQTPIQIRXIHWTIGM«GEPP]
MRXLIGLMPHGPEWW[LMGLSZIVVMHIXLIQIXLSHSJTEVIRXGPEWWMRXLIGLMPHGPEWW-RFSXLXLIGPEWWIW
XLIREQISJXLIQIXLSHXLIRYQFIVSJTEVEQIXIVWSJXLIQIXLSHERHMX WVIXYVRX]TIEPPEVIWEQI
MRFSXLTEVIRXERHGLMPHGPEWW
-RWMRKPIMRLIVMXERGIQIXLSH3ZIVVMHMRKXLIQIXLSHSJTEVIRXGPEWWMWSZIVVMHIH[MXLXLILIPTSJ
GLMPHGPEWWQIXLSHWSXLEXXLIQIXLSHSJGLMPHGPEWWI\IGYXIWMRWXIEHSJQIXLSHSJTEVIRXGPEWW
class Parent:
def call(self):
print("Parent Calling.....")
class Child(Parent):
def call(self):
print("Child Calling.....")
obj = Child()
[Link]()
Child Calling.....
1IXLSH3ZIVVMHMRKSRP]LETTIRWMRMRLIVMXERGIERHX]TIWSJMRLIVMXERGI
Multiple Inheritance Method Overriding
In Multiple Inheritance Method Overriding, we override the same method of more than one Parent
class to the same named method of Child class. So that child class access the same method by
class Mother:
def call(self):
print("Mother Calling...")
class Father:
def call(self):
print("Father Calling...")
Here, the derived class Son inherit with the class Mother and Father class. Now, the call() method
of Son class override the call() method of their Parent classes that is Mother and Father class.
objectChild = Son()
[Link]()
Son Calling...
In Multilevel Inheritance Method Overriding, we override the same named method in each level of
inheritance to its Parent class at that level. In each level of inheritance, same named method of
particular child class override the same named method of particular parent class and this happens
class Grand:
def call(self):
print("Grand Calling...")
class Parent(Grand):
def call(self):
print("Parent Calling...")
class Child(Parent):
def call(self):
print("Child Calling...")
First of all, we call the object of Parent class that override the call() method of Grand class.
objParent = Parent()
[Link]()
Parent Calling...
Then, we call the object of Child class that override the call() method of Parent class.
objectChild = Child()
[Link]()
Child Calling...
To override the method of parent class instead of method of child class. We use the super()
function and then dot after that calling the same named method which is present in all the
classes. So that in child class the method of parent class is overrided successfully
class Parent :
def call(self):
print("Parent Calling...")
Here, we call the call() with super() function so that the method of parent class will execute when
class Son(Parent):
def call(self):
super().call()
objectChild = Son()
[Link]()
Parent Calling...