Python Object-Oriented Programming Guide
Python Object-Oriented Programming Guide
A class is a collection of objects. A class contains the blueprints or the prototype from which the
objects are being created. It is a logical entity that contains some attributes and methods.
class ClassName:
# Statement-1
.
.
# Statement-N
Creating an Empty Class in Python
class Student:
pass
➢ Python Objects :
The object is an entity that has a state and behavior associated with it. It may be any real-world
object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even
arrays, and dictionaries, are all objects. More specifically, any single integer or any single string is an
object.
• State: It is represented by the attributes of an object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
• Identity: It gives a unique name to an object and enables one object to interact with other
objects.
To understand the state, behavior, and identity let us take the example of the class Student.
✓ Creating an Object :
obj = Student()
some basic keywords that will we used while working with objects and classes.
1. Python Self
• The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class. It holds the memory reference of object.
• It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:
2. The Python __init__ Method
class student:
def __init__(self,name,dept):
[Link]=name
[Link]=dept
def std_details(self):
print("Details of class student: ",[Link],[Link])
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
• Parameterized Constructor
• Non-parameterized Constructor
Creating the constructor in python
➢ In Python, the method the __init__() simulates the constructor of the class. This method is
called when the class is instantiated. It accepts the self-keyword as a first argument which
allows accessing the attributes or method of the class.
We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a
constructor, even if it simply relies on the default constructor.
Consider the following example to initialize the Employee class attributes.
Example :
class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name
def display(self):
print("employe details", [Link], [Link])
The parameterized constructor has multiple parameters along with the self.
Example :
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link]) Output:
This is parametrized constructor
student = Student(“anu") Hello anu
[Link]()
2. Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument.
Example:
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link](“anu")
➢ Python Default Constructor
When we do not include the constructor in the class or forget to declare it, then that becomes
the default constructor. It does not perform any task but initializes the objects.
Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()
SN Function Description
1 getattr (obj,name,default) It is used to access the attribute of the object.
It is used to set a particular value to the specific
2 setattr (obj, name,value)
attribute of an object.
3 delattr (obj, name) It is used to delete a specific attribute.
It returns true if the object contains some
4 hasattr(obj, name)
specific attribute.
Example
class Student:
def __init__(self, name, id, age):
[Link] = name
[Link] = id
[Link] = age
s = Student(“anu", 101, 22) # creates the object of the class Student
print(hasattr(s, 'id')) # prints true if the student contains the attribute with name id
print([Link]) # this will give an error since the attribute age has been
deleted
Output:
anu
23
True
AttributeError: 'Student' object has no attribute 'age'
DESTRUCTORS IN PYTHON
def __del__(self):
# body of destructor
Note : A reference to objects is also deleted when the object goes out of reference or
when the program ends.
Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all
references of object ‘obj’, therefore destructor invoked automatically.
obj = Employee()
del obj
➢ The destructor was called after the program ended or when all the references to object are
deleted i.e when the reference count becomes zero, not when object went out of scope.
EXAMPLE: # delete object reference s1
del s1
class Student:
print('After destroy of s1 ')
# constructor s2.student_details()
def __init__(self, name): del s2
[Link] = name
# create object
s1 = Student('Anu')
# create new reference
# both reference points to the same object
s2 = s1
s1.student_details()
Python Inheritance
➢ Inheritance is the capability of one class to derive or inherit the properties from another class.
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Creating a Parent Class
A parent class is a class whose properties are inherited by the child class. create a parent class called
Person which has a Display method to display the person’s information.
A child class is a class that drives the properties from its parent class. e1= Employee("Emy",11,"Female")
print([Link])
➢ Example of Inheritance in Python print([Link])
#parent class print([Link])
class Customer: print([Link])
def __init__(self,name): print(e1.__dict__)
[Link]=name
[Link]()
#child class inherit the property of parent class
class Employee(Customer): Output :
def __init__(self,name,age,gender): Emy
super().__init__(name) 11
[Link]=age Female
[Link]=gender 15000
[Link]=15000
{'name': 'Emy', 'age': 11, 'gender': 'Female',
'salary': 15000}
def show(self):
print("the name of Employee is ",[Link],"and age is ", the name of Employee is Emy and age is
[Link],"and gender is “ ,[Link],"salary is",[Link]) 11 and gender is Female salary is 15000
The super() Function
The super() function is a built-in function that returns the objects that represent the parent class. It
allows to access the parent class’s methods and attributes in the child class.
1. Single inheritance: When child class is derived from only one parent class.
Example:
Syntax of single inheritance:
class Parent: #parent_class
class class1: #parent_class
def method1(self):
pass
print("This is parent class")
class class2(class1): #child_class
class Child(Parent): #child_class
pass
def method2(self):
print("This is child class")
obj_name = class2()
c1=Child() # create object for child_class
c1.method1()
c1.method2()
2. Multiple Inheritance: When child class is derived or inherited from more than one parent
class.
• In multiple inheritance, we have two parent classes/base classes and one child class that
inherits both parent classes properties.
• It describes the idea of wrapping data and the methods that work on data within one unit.
• This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data.
• To prevent accidental change, an object’s variable can only be changed by an object’s method.
Those types of variables are known as private variables.
public
private
protected
➢ The public Access Modifier: The public member is accessible from inside or outside the class.
➢ The private Access Modifier : The private member is accessible only inside class. Define a private
member by prefixing the member name with two underscores.
Example : __age
➢ The protected Access Modifier : The protected member is accessible from inside the class
and its sub-class. Define a protected member by prefixing the
member name with an underscore.
Example : _age
Example : Example : To access the private variable, we have to create a
function and print the private variable inside the method. Call
class A(): the method from outside the method.
def __init__(self):
self.a=5 class A():
self._b=4 def __init__(self): Output :
self.__c=6 self.a=5
obj=A() self._b=4 value of a : 5
print(obj.a) self.__c=6 value of b : 4
print(obj._b) value of c : 6
print(obj.__c) #we can’t access the private variable def myfun(self):
print ("value of c :", self.__c)
Output :
obj=A()
AttributeError: 'A' object has no attribute '__c' print("value of a :", obj.a)
print ("value of b :", obj._b)
[Link]()
Data Abstraction in Python
➢ Data Abstraction in Python can be achieved through creating abstract classes and inheriting
them later.
Abstract Class : A class which contains one or more abstract methods is called an abstract class.
By default, Python does not provide abstract classes. Python comes with a module that
provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works
by decorating methods of the base class as abstract and then registering concrete classes as
implementations of the abstract base. We use the @abstractmethod decorator to define an
abstract method or if we don't provide the definition to the method, it automatically becomes the
abstract method.
Syntax :
from abc import ABC,@abstractmethod
class Classname(ABC)
Abstract method : An abstract method is a method that has a declaration but does not have an
implementation.
Syntax :
from abc import ABC,@abstractmethod
class Classname(ABC):
def metodname(self):
pass
Example - # Driver code
t= Tesla ()
from abc import ABC, abstractmethod [Link]()
class Car(ABC):
s = Suzuki()
def mileage(self):
[Link]()
pass
d = Duster()
class Tesla(Car): [Link]()
def mileage(self):
print("The mileage is 30kmph") Output:
The word polymorphism means having many forms. Polymorphism refers to having multiple
forms. Polymorphism is a programming term that refers to the use of the same function name,
but with different signatures, for multiple types.
class Apple():
def color(self):
print ("color is red")
def taste(self):
print ("always is sweet") Output:
def fruits(obj):
[Link]()
[Link]()
a_obj = Apple()
o_obj = Orange()
fruits(a_obj)
fruits(o_obj)
Python Exception Handling
➢ Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a
program due to which the program will stop the execution. On the other hand, exceptions are
raised when some internal events occur which change the normal flow of the program.
In Python, there are several built-in exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python:
1. SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code,
such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
2. TypeError: This exception is raised when an operation or function is applied to an object of
the wrong type, such as adding a string to an integer.
3. NameError: This exception is raised when a variable or function name is not found in the
current scope.
4. IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
5. KeyError: This exception is raised when a key is not found in a dictionary.
6. ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when
the string does not represent a valid integer.
8. IOError: This exception is raised when an I/O operation, such as reading or writing
a file, fails due to an input/output error.
[Link]: This exception is raised when an import statement fails to find or load a
module.
Difference between Syntax Error and Exceptions
• Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It
leads to the termination of the program.
Example:
amount = 10000
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results
in an error. This error does not stop the execution of the program, however, it changes the
normal flow of the program.
# initialize the amount variable Output:
Example: marks = 10000
1. try block
2. except block
3. else block
4. finally block
➢ Syntax :
else:
try: #code to execute if no exception occurred
#code containing exception finally:
except[exception name]: #always executed
#code to handle exception
➢ Try and Except Statement – Catching Exceptions
• Try and except statements are used to catch and handle exceptions in Python.
• Statements that can raise exceptions are kept inside the try clause and the statements that
handle the exception are written inside except clause.
A try statement can have more than one except clause, to specify handlers for different
exceptions.
The general syntax for adding specific exceptions are –
try:
Example : Output :
# statement(s)
except (exception name): num1 = 4 File"F:/python s4/try and [Link]", line 3, in <module>
# statement(s) num2 = 0 sum=num1/num2
except (exception name): sum=num1/num2 ZeroDivisionError: division by zero
# statement(s) print(sum)
Explanation - As we can see from the code above, a ZeroDivisionError error occurred. The reason
for this is that we are doing a 4 by 0 division here. Python understands that an integer cannot be
split by a zero. We apply exception handling techniques to deal with this exception.
except(ZeroDivisionError):
print("ZeroDivisionError handled ")
try: num1 =int(input("enter the first number : ")) enter the first number : 4
# statement(s) num2 = int(input("enter the second number : ")) enter the second number : 2
except (exception name): try: 2.0
# statement(s) sum is : 2.0
sum=num1/num2
else: print(sum)
# statement(s) except(ZeroDivisionError):
print("ZeroDivisionError handled ")
else:
print("sum is : ",sum)
• Python provides a keyword finally, which is always executed after the try and except blocks.
• The final block always executes after the normal termination of the try block or after the try block
terminates due to some exception.
Syntax: Example : Output :
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception.
The variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an error location.
The raise statement in Python is used to raise an exception. Try-except blocks can be
used to manage exceptions, which are errors that happen while a program is running. When an
exception is triggered, the program goes to the closest exception handler, interrupting the
regular flow of execution.
• The raise keyword is typically used inside a function or method, and is used to indicate an
error condition.
• We can throw an exception and immediately halt the running of your program by using the
raise keyword.
➢ Python looks for the closest exception handler, which is often defined using a try-except block,
when an exception is triggered.
➢ If an exception handler is discovered, its code is performed, and the try-except block's starting
point is reached again.
➢ If an exception handler cannot be located, the software crashes and an error message appears.
Advantages of Exception Handling:
1. Improved program reliability: By handling exceptions properly, you can prevent your program
from crashing or producing incorrect results due to unexpected errors or input.
2. Simplified error handling: Exception handling allows you to separate error handling code from the
main program logic, making it easier to read and maintain your code.
3. Cleaner code: With exception handling, you can avoid using complex conditional statements to
check for errors, leading to cleaner and more readable code.
4. Easier debugging: When an exception is raised, the Python interpreter prints a traceback that
shows the exact location where the exception occurred, making it easier to debug your code.
Performance overhead: Exception handling can be slower than using conditional statements to check
for errors, as the interpreter has to perform additional work to catch and handle the exception.
1. Increased code complexity: Exception handling can make your code more complex, especially if
you have to handle multiple types of exceptions or implement complex error handling logic.
2. Possible security risks: Improperly handled exceptions can potentially reveal sensitive information
or create security vulnerabilities in your code, so it’s important to handle exceptions carefully and
avoid exposing too much information about your program.
Python assert keyword
Python Assertions in any programming language are the debugging tools that help in the
smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants
to be true and hence puts them in code so that failure of these doesn’t allow the code to execute
further.
Assert Keyword in Python
In simpler terms, we can say that assertion is the Boolean expression that checks if the
statement is True or False. If the statement is true then it does nothing and continues the execution,
but if the statement is False then it stops the execution of the program and throws an error.
In Python, the assert keyword helps in achieving this task. This statement takes as input a
Boolean condition, which when returns true doesn’t do anything and continues the normal flow of
execution, but if it is computed to be false, then it raises an AssertionError along with the optional
message provided.
Parameters:
▪ Documentation: The use of assert statements in your code might act as documentation. Assert
statements make it simpler for others to understand and work with your code since they
explicitly describe the assumptions that your code is making.
▪ Testing: In order to ensure that certain requirements are met, assert statements are frequently
used in unit testing. You can make sure that your code is working properly and that any changes
you make don’t damage current functionality by incorporating assert statements in your tests.
▪ Security: You can use assert to check that program inputs comply with requirements and
validate them.
Regular Expression in Python
Python has a module named re that is used for regular expressions in Python. We can
import this module by using the import statement.
import re
1. findall() : finds *all* the matches and returns them as a list of strings, with each string
representing one match.
Syntax :
[Link](<pattern>, source_string)
Example :
import re Output :
str="hello everyone this is python"
x = [Link]("h",str) ['h', 'h', 'h']
print(x)
import re import re
str="hello everyone this is python" str="hello everyone this is python"
x=[Link]("h",str) x=[Link]("abc",str)
print(x) print(x)
Output : Output :
<[Link] object; span=(0, 1), match='h'> []
3. [Link]() : This method either returns None (if the pattern doesn’t match), or a
[Link] that contains information about the matching part of the
string. This method stops after the first match, so this is best suited for testing a
regular expression more than extracting data.
Example : If the pattern matches search method will return the match object :
import re
str="hello everyone this is python" Output :
x= [Link]("h",str) <[Link] object; span=(0, 1), match='h'>
print(x)
Example : If the pattern doesn't matches search method will return none :
import re Output :
str="hello everyone this is python" none
x=[Link]("abc",str)
print(x)
➢ Using the search method, it will only return match objects. To see the original result match
object, provide some methods.
1. start
2. span
3. String
Example: Output:
import re (6, 14)
str="hello everyone this is python"
x=[Link]("everyone",str)
print([Link]())
3. string(): string will return the actual string used for pattern matches.
Output: Output: ['', 'h', 'e', 'l', 'l', 'o', ' ', 'e', 'v', 'e', 'r',
['', 'ello everyone t', 'is is pyt', 'on'] ['', ' everyone this is python'] 'y', 'o', 'n', 'e' '']
Example:
5. sub() : substitute new string to old string
import re
Syntax: str="python programming"
[Link]("old_string","new_string",source_string) x=[Link]("p","r",str)
print(x)
Python RegEx Meta Characters Output : rython rrogramming
Metacharacters are part of regular expression and are the special characters that
symbolize regex patterns or formats. Every character is either a metacharacter or a regular
character in a regular expression. However, metacharacters have a special meaning. They are
not used to match any patterns but to define some rules to find the specific pattern in the
statement. Metacharacters are also known as operators, signs, or symbols.
Output : Output:
['hello’] []
Example : Output:
import re [python]
str="hello everyone this is python"
x=[Link]("python$",str)
print(x)
Example : if the pattern is not the last string
import re Output:
str="hello everyone this is python" []
x=[Link]("everyone$",str)
print(x)
example 1 : It checks if there are 3 characters before the pattern L. If yes, it will return that
pattern. If not, it will return an empty list.
import re output:
str="hello everyone this is python" [hello]
x=[Link]("...lo",str)
print(x)
example 2 : output:
import re
[hello eve]
str="hello everyone this is python"
x=[Link]("hel......",str)
print(x)
example 3 : output:
import re []
str="hello everyone this is python"
x=[Link]("python...",str)
print(x)
5. question mark (?) : matches zero or one occurrences of the regular expression.
7. asterisk (*) or star metacharacter : means “match zero or more occurrence of the
preceding character.”
Example 1: 1 occurrence of m Example 2: no occurrence of m Example 3: more occurrence of m
import re import re import re
str="amu" str="au" str="ammmmmmmu"
x=[Link]("am*u",str) x=[Link]("am*u",str) x=[Link]("am*u",str)
print(x) print(x) print(x)
Example 1: Example 2:
import re import re
str="my name is ammu, my ae is 20, i love my self" str="my name is ammu, my ae is 20, i love my self"
x=[Link]("my{1,3}",str) x=[Link]("my{5,6}",str)
print(x) print(x)
Output: Output:
['my', 'my', 'my'] []
Character Sets
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a - z] a to z
[A - Z] A to Z
[a - z A - Z] a to z , A to Z
[0 - 9] 0 to 9
Special Characters
1. \d Returns a match where the string contains digits (numbers from 0-9)
Example 1 : Example 2 :
import re import re
txt = "The rain 123" txt = "The rain "
#Check if the string contains any digits (numbers from 0-9): #Check if the string contains any digits (numbers from 0-9):
x = [Link]("\d", txt) x = [Link]("\d", txt)
print(x) print(x)
Output: Output:
['1', '2', '3'] []
Output : Output:
['r', 'a', 'i', 'n'] ['r', 'a', 'i', 'n', ' ']
3. \w Returns a match where the string contains any word characters (characters from a to Z,
digits from 0-9, and the underscore _ character)
Example 1: Example 2:
import re import re
txt = "The rain 123" txt = "The rain 123 &%#"
x = [Link]("\w", txt) x = [Link]("\w", txt)
print(x) print(x)
Output: Output:
['T', 'h', 'e', 'r', 'a', 'i', 'n', '1', '2', '3'] ['T', 'h', 'e', 'r', 'a', 'i', 'n', '1', '2', '3']
4. \W Returns a match where the string DOES NOT contain any word characters
Example 1: Example 2:
import re import re
txt = "The rain " txt = "The rain &**"
x = [Link]("\W", txt) x = [Link]("\W", txt)
print(x) print(x)
Output: Output:
[' ', ' '] [' ', ' ', '&', '*', '*']
5. \s Returns a match where the string contains a white space character
Example 1: Example 2:
import re import re
txt = "This is regular expression" txt = "regularexpression"
#Return a match at every white-space character: #Return a match at every white-space character:
x = [Link]("\s", txt) x = [Link]("\s", txt)
print(x) print(x)
Output: Output:
[' ', ' ', ' '] []
6. \S Returns a match where the string DOES NOT contain a white space character
Example 1: Example 2:
import re import re
txt = "Python" txt = "Python"
#Return a match at every NON white-space character: #Return a match at every NON white-space character:
x = [Link]("\S", txt) x = [Link]("\S", txt)
print(x) print(x)
Output: Output:
['P', 'y', 't', 'h', 'o', 'n'] ['P', 'y', 't', 'h', 'o', 'n']
7. \b Returns a match where the specified characters are at the beginning or at the end of a word
Example 1: Example 2:
import re import re
txt = "hello World" txt = "hello World"
#Check if "hello" is present at the beginning of a WORD: #Check if "ello" is present at the beginning of a WORD:
x = [Link]("\bhello", txt) x = [Link]("\bello", txt)
print(x) print(x)
Output: Output:
['hello'] []
Example 1:
Example 2:
import re
import re
txt = "The rain"
txt = "The rain"
#Check if "ain" is present at the end of a WORD:
#Check if "ra" is present at the end of a WORD:
x = [Link](r"ain\b", txt)
x = [Link]("ra\b", txt)
print(x)
print(x)
Output:
Output:
['ain']
[]
Returns a match where the specified characters are present, but NOT at the beginning (or at the end)
8. \B of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw string")
Example 1: Example 2:
import re import re
txt = "The rain" txt = "The rain"
#Check if "ain" is present, but NOT at the beginning of a word: #Check if "ain" is present, but NOT at the end of a word:
x = [Link](r"\Bain", txt) x = [Link](r"ain\B", txt)
print(x) print(x)
Output: Output:
['ain'] []
9. \Z Returns a match if the specified characters are at the end of the string
Example:
import re Output:
txt = "The rain" ['rain']
#Check if the string ends with “rain":
x = [Link]("rain\Z", txt)
print(x)