PYTHON CONCEPT
MODULES - 2
Prince Kumar
EXCEPTION HANDLING:
Exception handling in Python is a mechanism that
allows you to handle errors and unexpected situations in
a program gracefully. When an error occurs during the
execution of a Python program, an exception is raised.
Exception handling enables you to catch and respond to
these exceptions, preventing your program from crashing
and providing a way to recover or gracefully exit.
EXCEPTION HANDLING:
### Basic Syntax:
```python
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the specific exception (ZeroDivisionError in
this case)
print("Cannot divide by zero!")
EXCEPTION HANDLING:
except Exception as e:
# Generic exception handler
print(f"An unexpected error occurred: {e}")
else:
# Optional: Code to execute if no exception is raised
print("No exception occurred.")
finally:
# Optional: Code that will be executed regardless of whether
an exception occurred or not
print("This block always runs.")
```
EXCEPTION HANDLING:
In this example:
- The `try` block contains the code that might raise an exception.
- The `except` block catches specific exceptions (in this case,
`ZeroDivisionError`). You can have multiple `except` blocks to
handle different types of exceptions.
- The `else` block contains code to be executed if no exception is
raised in the `try` block.
- The `finally` block contains code that is always executed,
whether an exception occurred or not.
EXCEPTION HANDLING:
### Handling Multiple Exceptions:
```python
try:
result = 10 / 0
except (ZeroDivisionError, ValueError) as e:
print(f"An error occurred: {e}")
```
You can catch multiple exceptions in a single `except` block by
providing a tuple of exception types.
CLASS:
In Python, a class is a blueprint for creating objects, providing a
way to structure and model the functionality and data associated
with those objects. Objects are instances of a class, and they can
have attributes (data) and methods (functions) associated with
them.
CLASS:
### Basic Class Syntax:
```python
class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
def method1(self):
print("Method 1 called.")
def method2(self):
print("Method 2 called.")
```
CLASS:
- The `__init__` method is a special method called the
constructor, which is executed when an object is created. It
initializes the attributes of the object.
- `self` is a reference to the instance of the class. It is a
convention in Python to use `self` as the first parameter of
instance methods.
CLASS:
### Creating Objects (Instances):
```python
# Creating an instance of MyClass
my_object = MyClass(attribute1_value, attribute2_value)
```
CLASS:
### Accessing Attributes and Calling Methods:
```python
# Accessing attributes
value = my_object.attribute1
# Calling methods
my_object.method1()
```
CLASS:
### Inheritance:
Classes can inherit attributes and methods from other classes,
creating a hierarchy of classes. This is known as inheritance.
```python
class ChildClass(MyClass):
def __init__(self, attribute1, attribute2, attribute3):
super().__init__(attribute1, attribute2)
self.attribute3 = attribute3
def method3(self):
print("Method 3 called.")
```
CLASS:
### Encapsulation:
Attributes of a class can be encapsulated by making them private (adding a double
underscore `__` prefix). This restricts direct access to those attributes from outside
the class.
```python
class MyClass:
def __init__(self, attribute1, attribute2):
self.__attribute1 = attribute1
self.__attribute2 = attribute2
def get_attribute1(self):
return self.__attribute1
def set_attribute1(self, value):
self.__attribute1 = value
```