4. 4
Python Basics
Introduction of Python 3
Python is a general-purpose interpreted, Interactive, object-oriented and high-level scripting language developed in the late 1980s by Guido van Rossum at the National Research Institute for
Mathematics and Computer Science in the Netherlands. The initial version was published at the alt.sources newsgroup in 1991, and version 1.0 was released in 1994.
The name Python, by the way, derives not from the snake, but from the British comedy troupe Monty Python’s Flying Circus, of which Guido was, and presumably still is, a fan. It is common to find
references to Monty Python sketches and movies scattered throughout the Python documentation.
Meanwhile, Python 3.7.4 is the latest version of Python 3, released in 2019.
Python Features:
• Easy to learn
• Easy to read
• Easy to maintain
• A broad standard library
• Interactive mode
• Portable
• Extendable
• Database
• GUI Programming
• Scalable
Let's proceed for Environment Setup---🡪
5. Environment Setup
Python 3 is available for windows, Mac OS & most of the flavours of Linux OS.
1. Download the latest version from the official site ( https://www.python.org/ )
2. Install the .exe file & add the major folders paths to the environment variable.
3. Verify whether Python is installed or not and check the version. [“python -V”] & [“where python”]
4. Install latest pip3 by the help of command prompt [“pip3” or “pip3 help install”] & [pip3 install –upgrade pip] & [pip3 -V] & [“where pip3”]
5
6. 6
Keywords
Keywords are special words which are reserved and have a specific meaning. Python has a set of keywords that cannot be used as variables in programs. All keywords in Python are case
sensitive. So, you must be careful while using them in your code. We’ve just captured here a snapshot of the possible Python keywords.
---------------------------------------------------------------------------------------------------------------------------------------
Hence, to get hold of the up-to-date list, you can open Python shell and run the following commands as shown in the
below snippet.
1. help()
2. help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
7. Data Types and Variable
7
Variable
Variables are nothing but the reserved memory locations to store values. It means that when you create a variable, you reserve some space in the memory.
The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.
For example-
KM = 100 # An Integer assignment
Metre = 1000.0 # A floating point
Name = “Rajeev” # A string
In python Identifiers must obey the following rules:
• All identifiers must start with letter or underscore ( _ ) , you can’t use digits. For e.g my_var is valid identifier while 1digit is not.
• Identifiers can contain letters, digits and underscores ( _ ).
• They can be of any length.
• Identifier can’t be a keyword (keywords are reserved words that Python uses for special purpose) [help()]
Multiple Assignment
Python allows to assign a single value to or multiple value to several variables simultaneously.
For example-
A = B = C = 10
OR
A = B = C = 1, 20.0, “Rajeev”
Data Types
The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value and has or her address is stored as alphanumeric characters.
Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.
Python has five standard data types:-
Numbers
String
8. 8
Basic Operators
Operators are the constructs, which can manipulate the value of operands. Here we consider the expression (4 + 5 = 9). What we call here 4 & 5 is operands and the plus symbols ( + ) is the
operator.
Types of Operators in Python: Arithmetic, Comparison (Relational), Assignment, Logical, Bitwise, Membership, Identity Operators.
Arithmetic
This are used to perform mathematical operations like addition, subtraction, multiplication and division.
Operators are: + , - , *, /, %, ** Exponent, // Floor Division
Comparison (Relational)
These operator compares the values. It either returns True or False according to the condition.
Operators are: ==, !=, >, >=, <, <=
Assignment
Assignment operators are used to assign values to the variables. Operators are: =, +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=
Logical
Logical operators perform Logical AND, Logical OR and Logical NOT operations.
Operators are:- and, or, not
Bitwise
Bitwise operators acts on bits and performs bit by bit operation.
Operators are:- &,|, ^, ~, >>, <<
Membership
in and not in are the membership operators; used to test whether a value or variable is in a sequence, such as string, lists, or tuples.
Operators are:- in, not in
Identity Operators
is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal does not imply that they are identical.
Operators are:- is, is not
9. 9
Decision Making
There comes situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arises in programming also where
we need to make some decisions and based on these decision, we will execute the next block of code.
Decision making statements in programming languages decides the direction of flow of program execution.
Python programming language assumes any non-zero & non-null values as TRUE, and any zero or null values as FALSE value.
Decision making statements available in python are:
if statement if..else statements if-elif ladder nested if statements
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if statement
The if statement contains a
logical expression using
which the data is compared
and a decision is made
based on the results of the
comparison. It is used to
decide whether a certain
statement or block of
statements will be executed
or not, therefore if a certain
condition is true then a
block of statement is
executed otherwise not.
Syntax: if (expression):
# Executes this block
(s)
If..else
statement
An else statement can be
combined with an if
statement. An else
statement contains the
block of code that executes
if the conditional
expression in the if
statement resolves to 0 or a
FALSE value.
Syntax :
if (condition):
# Executes this block if
condition is true
else:
# Executes this block if
condition is false
If..elif
statement
The elif statement allows
you to check multiple
expressions for TRUE and
execute a block of code as
soon as one of the
conditions evaluates to
TRUE.
Syntax :
if (condition 1):
# Executes this block
if condition is true (s)
elif (condition 2):
# Executes this block if
condition is true (s)
elif (condition 3):
# Executes this block if
condition is true (s)
else:
# Executes this block if
condition is false
nested If
statement
A nested if is an if statement that is the
target of another if statement. Nested if
statements means an if statement inside
another if statement.
In a nested if construct, you can have an
if...elif...else construct inside another
if...elif...else construct.
Syntax :
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition1 & 2 is
true
elif (condition3):
# Executes when condition3 is true
elif (condition4):
# Executes when condition4 is true
else:
# Executes when is false
else:
# Executes when is false
10. 10
Loop
A Loop statement allows us to execute a statement or group of statement multiple times. Python provides three ways for executing the loops
while Loop | for in Loop
---------------------------------------------------------------------------------------------------------------------------------------
while Loop
while loop is used to execute a block of
statements repeatedly until a given a
condition is satisfied. And when the
condition becomes false, the line
immediately after the loop in program is
executed.
Syntax: While (Condition or
Expression):
# Executes this block (s)
statement 1
statement 2
OR
The else is only executed when your
while condition becomes false. If you
break out of the loop, or if an exception is
raised, it won’t be executed.
Syntax: While (Condition or
Expression):
# Executes this block (s)
else:
# Executes this block if
condition is false
for in Loop
The Python For Loop is used to repeat a
block of statements until there is no
items in Object may be String, List, Tuple
or any other object in python. For loop is
one of the mostly used loop in any
programming language.
Syntax: for iterator_var in sequence:
statements(s)
OR
The else is only executed when your for
condition becomes false. If you break out
of the loop, or if an exception is raised, it
won’t be executed.
Syntax: for iterator_var in sequence:
# Executes this block (s)
else:
# Executes this block if
condition is false
11. 11
Break, Continue & Pass Statement
The Python Break, Continue & Pass Statements are three important statements used to alter the flow of a program in any programming language. Loops are used to execute certain block of
statements for n number of times until the test condition is false. There will be some situations where we have to terminate the loop without executing all the statements. In these situations,
we can use the Python Break, Continue & Pass Statements.
---------------------------------------------------------------------------------------------------------------------------------------
The Python Break statement is very useful to exit from any loop such as For Loop, While Loop and Nested Loops. While executing these loops, if the compiler finds
the break statement inside them, the compiler will stop executing the statements inside the loop and exit immediately from the loop.
Syntax:
break
Continued…..
12. 12
Break, Continue & Pass Statement
The Python Continue statement is another one to control the flow of loops. This statement is used inside For Loop and While Loops. While executing these loops, if
compiler finds the python continue statement inside them, then the compiler will stop the current iteration and starts the new iteration from the beginning.
Syntax:
continue
Continued…..
13. 13
Break, Continue & Pass Statement
The pass keyword is used as a placeholder. "pass" is a special statement in Python that does nothing. It only works as a dummy statement. If you have an empty function definition, you would
get an error without the pass statement. The pass keyword can also be used in empty class definitions.
Syntax:
pass
14. 14
Numbers
Numbers data types store numeric values. And changing the value of a number data type results in a newly allocated object.
Number objects are created when a value is being assigned.
Example: value1 = 25, value2 = 30
Python Supports different numerical types-
1. int (Integers) EX- 10, -786, 080, -0786, -0x260, 0x69
2. float (Floating Point Real Value) Ex- 0.0, 15.20, -21.9, 32.3+e18, -90. , -32.54e100, 70.2-E12
3. complex (Complex Numbers) 3.14j, 45.j, 9.322e-36j, .876j, -.6545+0J, 3e+26J, 4.53e-7j
15. 15
Strings
A string is usually a bit of text you want to display to someone, or "export" out of the program you are writing. Python knows you want something to be a string when you put either "
(double-quotes) or ' (single-quotes) around the text. You saw this many times with your use of print when you put the text you want to go inside the string inside " or ' after the print to print the
string.
Example:
Value_1 = ‘ Rajeev Kumar Pramanik ’
Value_2 = “ Rajeev Kumar Pramanik ”
To access substrings, python uses the square brackets for slicing along with the index to obtain the substring.
16. 16
Lists
A list is a sequence of multiple values in an ordered sequence. Unlike Python Strings, List allow us to store different types of data such as integer, float, string etc. Lists in Python can be created
by just placing the sequence inside the square brackets[]. A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a
sequence at the time of list creation.
Other features that helps updating the List are:
1. Adding Elements to a List
2. Accessing elements from the List
3. Removing Elements from the List
4. Slicing of a List
Example:
List_Name = [] is an empty list that contains no values.
Integer_List = [1, 2, 3, 4, 5] is an integer list that contains five integer values.
String_List = [‘apple’, ‘Orange’, ‘Grape’, ‘Mango’] is a string list that contains four string values.
Mixed_List = [‘apple’, 2, 3.50, ‘Mango’] is a mixed list that contains one integer, one float and two integer values.
17. 17
Tuples
A data structure consisting of multiple parts, (in a relational database) an ordered set of data constituting a record.
The Python Tuple is almost similar to Python List except that the Tuples are immutable and Lists are mutable. It means, Once we declare the Tuple, we can’t change the values or items inside the
tuple, something like Constant keyword in other programming languages.
A Python Tuple is a sequence of multiple values in an ordered sequence.
Since it is immutable, Traversing Tuple is much faster than List.
Tuples are declared using Open and Closed Parenthesis ( )
Unlike Python Strings, Tuple allow us to store different types of data such as integer, float, string etc.
The following are the list of available ways to declare a Tuple in Python
Example:
Tuple_Name = () is an empty Tuple that contains no values.
Integer_Tuple = (1, 2, 3, 4, 5) is an integer tuple that contains five integer values.
String_Tuple = (‘apple’, ‘Orange’, ‘Grape’, ‘Mango’) is a string tuple that contains four string values.
Mixed_Tuple = (‘apple’, 2, 3.50, ‘Mango’) is a mixed tuple that contains one integer, one float and two integer values.
Nested_Tuple = (‘Python’, ‘Tutorial’, (1, 2, 3) ) is an example of tuple inside another tuple (Nested Tuple)
List_Tuple = (‘Python’, ‘Tutorial’, [1, 2, 3] ) is an example of List inside a tuple
18. 18
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single
value as an element, Dictionary holds {key:value} pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a
Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.
A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings,
Integers and tuples, but the key-values can be repeated and be of any type.
Keys are unique within a dictonary while values may not be.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing to curly braces{}.
Syntax:
myDict = {<key>:<value>, <key>:<value>, <key>:<value>}
19. 19
Date & Time
Python has a module named datetime to work with dates and times.
we can import a module named datetime to work with dates as date objects.
The strftime() Method
The datetime object has a method for formatting date objects into readable strings.
The method is called String Formatted Time [ strftime() ], and takes one parameter, format, to specify the format of the returned string.
20. 20
Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions is set of statements that take inputs, do some specific computation and produces
output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the
function. We can pass data, known as parameters, into a function. A function can return data as a result.
Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions.
Here are simple rules to define a function in Python:
❖ Function blocks begin with the keyword def followed by the function name and
parenthesis (()).
❖ Any input parameters or arguments should be placed within these parentheses.
Parameters can be defined inside the parenthesis.
❖ The first statement of a function can be an optional statement – the
documentation string of the function or docstring.
❖ The code block within every function starts with a colon (:) and is indented.
❖ The return statement [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return none.
Syntax:
def function_name ( parameters ):
“ function_docstring”
function_suite
return [ expression ]
Cycle Parts
21. 21
Special Methods
Classes in Python programming language can implement certain operations with special method names. These methods are not called directly but by a specific language syntax.
22. 22
Modules
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use.
A module is a file consisting of Python code.
A module can define functions, classes and variables.
A module can also include runnable code.
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
The import statement:
We can use any Python source file as a module by executing an import statement in some other Python source file.
When an interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that
the interpreter searches for importing a module. For example, to import the module calc.py, we need to put the following command at the top of the script :
# importing module calc.py
import calc
print add(10, 2)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The from import Statement:
Python’s from statement lets you import specific attributes from a module. The from .. import .. has the following syntax :
# importing sqrt() and factorial from the module math
from math import sqrt, factorial
# if we simply do "import math", then math.sqrt(16) and math.factorial() are required.
print sqrt(16)
print factorial(6)
23. 23
Files I/O
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g. hard disk).
Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform the operation)[rename(), remove(), mkdir(), chdir(), getcwd(), rmdir()]
3. Close the file
❖ Printing to the Screen:
The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a
string and writes the results to standard output as follows-
print (“Python is really a great language,”, “isn’t it?”)
------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
❖ The input Function:
The input([prompt]) function is equivalent to raw_input(), except that it assumes that the input is a valid Python expression and returns the evaluated results to you.
# Example
print(input(“Enter your name: ”))
print(int(input(“Enter your age: ”)))
❖ Reading Keyboard Input:
Python 2 has two built-in functions to read data from standard inputs, which by defaults comes from the keyboard. These
functions are input() and raw_input()
In Python 3 raw_input() function is deprecated. Moreover, input() functions read data from keyboard as string, irrespective of
wheather it is enclosed with quotes (“ or “”) or not.
Continued…..
24. 24
Files I/O
❖ Opening, Read & Write and Closing Files:
Python provides basic functions and methods necessary to manipulate files by default. Most of the file manipulations can be done by using a FILE Object.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Open a file:
Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
file = open("File_Open_Close_Read_Write.txt") # open file in current directory
OR
file = open("G:Manual+AutomationjUST-aUTOMATEPython_Programesorg.pythonFile_Open_Close_Read_Write.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or
binary mode.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Write a file:
To write into a file in Python, we need to open it in write 'w’. We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous data are erased. Writing a
string or sequence of bytes (for binary files) is done using a write() method.
file = open("G:Manual+AutomationjUST-aUTOMATEPython_Programesorg.pythonFile_Open_Close_Read_Write.txt", "w") # specifying full path
file.write("Hey ! this is Rajeev Kumar Pramanik.nI am from jUST~aUTOMATE Channel.n")
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Read a file:
To read into a file in Python, we need to use the read() method to read in size number of data. This method reads a string from an open file.
str = file.read(100)
print("The file that has data to be read is: ", str)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Close a file:
After completing all task, then the file need to be closed, so to close a file in Python, we need to use the close() method.
file.close(100)
25. 25
Exceptions
A Python program terminates during the execution of a program as soon as it encounters an error. In Python, an error can be a syntax error or an exception.
When the Python program encounters a situation that disrupts the flow of the program, it raises an exception that can be handled. If not handled properly, the interpreter throws a traceback
error along with the statements that caused that error. These exceptions prevent the program from crashing.
Why use exceptions:
When we write a program, there might be some possible errors that can happen down the line. If there is no backup mechanism to handle these errors, the program will simply crash. So, Python
exception handling is a mechanism in which we define a backup plan for a possible error situation.
There are two types of exceptions in Python:
Built-in Exceptions: Built-in exceptions are the standard exceptions defined in Python. These exceptions are raised when the program encounters an illegal operation like semantic errors.
User-Defined Exceptions: As the name goes by the exceptions defined by a user are called User-Defined Exceptions. Sometimes in a program, we need to create custom exceptions to serve our
own purposes. Python also allows us to create our own exceptions by deriving classes from the standard built-in exceptions.
Here is only a few tabulated list of some of the exceptions:
AssertionError: Raised in case of assertion statement failure.
IOError: Raised if an input/output operation fails.
ImportError: Raised when the imported module is not available or found.
IndentationError: Raised when the interpreter encounters incorrect indentation.
SyntaxError: Raised when a syntactical error is encountered.
TypeError: Raised when a function is using an object of the incorrect type.
ZeroDivisionError: Raised If the second operand of division or modulo operation is zero.
KeyboardInterrupt: Raised when the user hits interrupt key (Ctrl+c or delete).
Syntax:
try:
** Operational/Suspicious Code
except SomeException:
** Code to handle the exception
The finally Clause:
You can use a finally: block along with a try: block.
The finally: block is a place to put any code that must execute, whether the try: block raised an exception or not.
26. 26
Introduction to OOPs in Python
Python is a multi-paradigm programming language. Meaning, it supports different programming approach in different patterns.
One of the popular approach to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP).
An object has two characteristics:
Attributes
Behavior
Let's take an example:
Parrot is an object,
name, age, color are attributes
singing, dancing are behavior
The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don't Repeat Yourself).
In Python, the concept of OOP follows some basic principles:
Inheritance: A process of using details from a new class without modifying existing class.
Encapsulation: Hiding the private details of a class from other objects.
Polymorphism: A concept of using common operation in different ways for different data input.
Data Abstraction: Abstraction is one of the key concepts of object-oriented programming (OOP) languages. Its main goal is to handle complexity by hiding unnecessary details from the user. Also
called Implementation hiding
27. 27
Class & Objects
A class is a code template for creating objects. A class is a user-defined or user-created 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 variable) and methods, accessed via dot notation or It is a
combination of initializing variables, defining methods, static methods, class methods, etc. A class is a
formal description of how an object is designed, i.e. which attributes and methods it has. These objects are
called instances as well.
Here are simple rules to define a class in Python:
❖ Class blocks begin with the keyword “class” followed by the class name and parenthesis (()) & colon (:).
❖ Any input parameters or arguments should be placed within these parentheses. Parameters can be
defined inside the parenthesis.
❖ The code block within every class starts with a colon(:) and is indented.
Syntax:
class class_name():
gobal_variable = “string”
def function_name ( parameters ):
“ function_docstring”
local_variable = numbers
function_suite
return [ expression ]
Objects, __init(), Self & Instance:
❖ Object is one of the instances of the class. which can perform the functionalities which are defined in the class.
❖ To create instances of a class, have to call the class by using class name and pass in whatever arguments its __init__ method accepts. "__init__" is a reserved method in python classes. The
first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of the class.
❖ Self : The self represents the instance of the class. By using the "self" keyword we can access the attributes and methods of the class in python.
The reason you need to use self, is because Python does not use the “@” syntax to refer to instance attributes.
❖ The attribute reference uses ClassName.Variable_name or ClassName.function_name. For the instantiation, you have to create an instance of that class (or a copy of that class).
To create an instance use instance_name = class_Name(), to call the variable instance_name.variable_name and to call the method instance_name.method_name()
28. 28
Class Inheritance
Python inheritance means creating a new class that inherits (takes) all the functionalities from the parent class and allows to add more.
The new class that we created by inheriting functionalities is called as Child Class (or Derived Class or Sub Class). The class from which we inherit
is called Base Class or Parent Class or Super Class.
Instead of starting from scratch, by creating a class and deriving it from a pre-existing class by listing the parent class in parenthesis after the
new class name.
It refers to defining a new class with little or no modification to an existing class.
Syntax:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
The child class inherits the attributes of its parent class, and can use those attributes as if they were defined in the child class.
A child class can also override data members and methods from the parent.
This results into code reusability, readability and scalability. It reduces the code repetition. By dividing the code into multiple classes, the
applications look better, and the error identification will be easy.
29. 29
Encapsulation :— Information hiding
Using OOP in Python, we can restrict access to methods and variables. This prevent data from direct modification which is called encapsulation. In Python, we denote private attribute using
underscore as prefix i.e. single “ _ “ or double “ __“.
Encapsulation is the packing of data and functions operating on that data into a single component and restricting the access to some of the object’s components.
Encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
Protected members:
Protected member is (in C++ and Java) accessible only from within the class and it’s subclasses.
How to accomplish this in Python? The answer is — by convention. By prefixing the name of your member
with a single underscore, you’re telling others “don’t touch this, unless you’re a subclass”.
Private members:
But there is a method in Python to define Private: Add “__” (double underscore ) in front of the variable
and function name can hide them when accessing them from out of class.
Python doesn’t have real private methods, so one underline in the beginning of a method or attribute
means you shouldn’t access this method. But this is just convention. I can still access the variables with
single underscore.
Also when using double underscore (__).we can still access the private variables.
30. 30
Polymorphism
The polymorphism is the process of using an operator or function in different ways for different data input.
In practical terms, polymorphism means that if class B inherits from class A, it doesn't have to inherit everything about class A; it can do some of the things that class A does differently.
Polymorphism is mostly used when dealing with inheritance.
31. 31
Methods Overriding
In Method Overriding, the subclass has the same method with the same name and exactly the same number and type of parameters and same return type as a superclass.
It means creating two methods with the same name but differ in the programming logic. The concept of Method overriding allows us to change or override the Parent Class function in the Child
Class.
Example: # Python Method Overriding
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
In Python, to override a method, you have to meet certain conditions and they are:
❖ You can’t override a method within the same class. It means you have to do it in the child class using the Inheritance concept.
❖ To override the Parent Class method, you have to create a method in the Child class with the same name and the same number of parameters.
❖ Overriding is a kind of polymorphism. Polymorphism means “one name, many forms”. It is a run time polymorphism.
❖ Method Overriding is to “Change” existing behavior of the method.
❖ It always requires inheritance in Method Overriding.
❖ In Method Overriding, methods have the same name and same signature but in the different class.
❖ Method Overriding requires at least two classes for overriding.
32. 32
Methods Overloading
In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order.
Like other languages (for example method overloading in C++) do, python does not supports method overloading.
We may overload the methods but can only use the latest defined method.
Example: # Python Method Overloading
class Employee:
def message(self):
print('This message is from Employee Class’)
def message(self):
print('This Department class is inherited from Employee')
emp = Employee()
emp.message()
In Python, to overloading a method, you have to meet certain conditions and they are:
❖ Method Overloading is to “add” or “extend” more to the method’s behavior.
❖ Overloading is a kind of polymorphism. Polymorphism means “one name, many forms”. It is a compile-time polymorphism.
❖ It may or may not need inheritance in Method Overloading.
❖ In Method Overloading, methods have the same name different signatures but in the same class.
❖ Method Overloading does not require more than one class for overloading.
33. Conclusion
Before concluding I would like to say the viewer’s that before you start doing Automation Testing, you need to know the
root of testing, that is Manual Testing. Have to know basic things, and very important is the 7 Principles, Types of Testing,
STLC, Test Scenarios, Black Box Testing Techniques & based on the Scenarios have to create Test Case’s. Similarly in
Automation Testing have to write scripts based on the Scenarios. Creating Scenarios against an application to test is very
much important.
Otherwise the script is of no use.
Give your dedication & love towards any work, surely will get succeed.
Thank You!
33