Oops 3 Python DSA Notes 5
Oops 3 Python DSA Notes 5
1
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
The given Python code uses the ABC class and defines an abstract base class:
class AbstractClass(ABC):
@abstractmethod
def do_something(self): #Our abstract method declaration
pass
Note:
● You are required to define (implement) all the abstract methods declared in
an Abstract class, in all its subclasses to be able to instantiate the subclass.
For example, We will now define a subclass using the previously defined abstract
class. You will notice that since we haven't implemented the do_something method,
in this subclass, we will get an exception.
class TestClass(AbstractClass):
pass #No definition for do_something method
x = TestClass(4)
2
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
We will do it the correct way in the following example, in which we define two
classes inheriting from our abstract class:
class add(AbstractClass):
def do_something(self):
return self.value + 42
class mul(AbstractClass):
def do_something(self):
return self.value * 42
x = add(10)
y = mul(10)
print(x.do_something())
print(y.do_something())
52
420
Thus, we can observe that a class that is derived from an abstract class cannot be
instantiated unless all of its abstract methods are overridden.
Note: Concrete classes contain only concrete (normal) methods whereas abstract
classes may contain both concrete methods and abstract methods.
3
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
● Similarly, we can even have concrete methods in the abstract class that can
be invoked using super() call. Since these methods are not abstract it is not
necessary to provide their implementation in the subclasses.
● Consider the given example:
class AbstractClass(ABC):
@abstractmethod
def do_something(self): #Abstract Method
print("Abstract Class AbstractMethod")
class AnotherSubclass(AbstractClass):
def do_something(self):
#Invoking the Abstract method from super class
super().do_something()
4
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
Another Example
The given code shows another implementation of an abstract class.
# Driver code
R = Human()
R.move()
K = Snake()
K.move()
R = Dog()
R.move()
5
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
Exception Handling
Error in Python can be of two types i.e. Syntax errors and Exceptions.
● Errors are the 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 changes the normal flow of the program.
amount = 10000
if(amount>2999)
print("Something")
The syntax error is because there should be a “:” at the end of an if statement.
Since it is not present, it gives a syntax error.
Exceptions: Exceptions are raised when the program is syntactically correct but the
code resulted in an error. This error does not stop the execution of the program,
however, it changes the normal flow of the program.
Example:
marks = 10000
a = marks / 0
print(a)
6
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
Output:
Exceptions in Python
● Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
● When these exceptions occur, the Python interpreter stops the current
process and passes it to the calling process until it is handled.
● If not handled, the program will crash.
● For example, let us consider a program where we have a function A that calls
function B, which in turn calls function C. If an exception occurs in function C
but is not handled in C, the exception passes to B and then to A.
● If never handled, an error message is displayed and the program comes to a
sudden unexpected halt.
7
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
Catching Exceptions
In Python, exceptions can be handled using try-except blocks.
● If the Python program contains suspicious code that may throw the
exception, we must place that code in the try block.
● The try block must be followed by the except statement, which contains a
block of code that will be executed in case there is some exception in the try
block.
● We can thus choose what operations to perform once we have caught the
exception.
8
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
print()
The entry is a
Oops! <class 'ValueError'> occurred.
The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
The entry is 2
The reciprocal of 2 is 0.5
Every exception in Python inherits from the base Exception class. Thus we can
write the above code as:
l = ['a', 0, 2]
for ele in l:
try:
print("The entry is", ele)
9
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
r = 1/int(ele)
except Exception as e: #Using Exception class
print("Oops!", e. class , "occurred.")
print("Next entry.")
print()
print("The reciprocal of", ele, "is", r)
● In the above example, we did not mention any specific exception in the
except clause.
● This is not a good programming practice as it will catch all exceptions and
handle every case in the same way.
● We can specify which exceptions an except clause should catch.
● A try clause can have any number of except clauses to handle different
exceptions, however, only one will be executed in case an exception occurs.
● You can use multiple except blocks for different types of exceptions.
● We can even use a tuple of values to specify multiple exceptions in an except
clause. Here is an example to understand this better:
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
10
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
try-except-else Statements
We can also use the else statement with the try-except statement in which, we can
place the code which will be executed in the scenario if no exception occurs in the
else block. The syntax is given below:
try:
c = 2/1
11
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Output:
Hi I am else block
We get this output because there is no exception in the try block and hence the else
block is executed. If there was an exception in the try block, the else block will be
skipped and except block will be executed.
finally Statement
12
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
The try statement in Python can have an optional finally clause. This clause is
executed no matter what and is generally used to release external resources.
Here is an example of file operations to illustrate this:
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This type of construct makes sure that the file is closed even if an exception occurs
during the program execution.
try:
13
Fahad sayyed – notes DSA 5 oops
Linked in @ fahad sayyed
a = -2
if a <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
14