0% found this document useful (0 votes)
10 views

Chapter 6 Python

Persistanse and oop in python...by eyob

Uploaded by

bitanyatekle84
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Chapter 6 Python

Persistanse and oop in python...by eyob

Uploaded by

bitanyatekle84
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Computer Programming

Persistence and OOP

Eyob S.

SITE, AAiT

July 2, 2024

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 1 / 42


Table of Contents

1 Persistence

2 Object Oriented Programming

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 2 / 42


Persistence

Persistence

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 3 / 42


Persistence in Programming

Persistence refers to the characteristic of data that outlives the exe-


cution of the program that created it.

Data stored in variables and data structures is temporary and lost when
the program terminates.

To make data persistent, it needs to be saved to a permanent storage


medium, such as a file or a database.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 4 / 42


File Handling

File handling in Python allows us to store data permanently by writing


it to files, and retrieve it later by reading from those files.

Python has several functions for creating, reading, updating, and delet-
ing files.

The key functions for working with files in Python are open(), read(),
write(), and close().

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 5 / 42


The open() Function

The open() function is used to open a file and return a file object.

The syntax of the open() function is:

file_object = open(filename, mode)

The filename parameter is the name of the file you want to open.

The mode parameter specifies the mode in which the file is opened:

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 6 / 42


File opening modes

'r' - Opens the file for reading.

'w' - Opens the file for writing (creates a new file or truncates an
existing file).

'a' - Opens the file for appending data to the end.

'r+' - Opens the file for both reading and writing.

'b' - Binary mode. Used in combination with other modes (e.g., 'rb',
'wb').

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 7 / 42


Examples of Using the open() Function

# Open a file for reading


file = open("example.txt", "r")

# Open a file for writing


file = open("example.txt", "w")

# Open a file for appending


file = open("example.txt", "a")

# Open a file for both reading and writing


file = open("example.txt", "r+")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 8 / 42


Reading a File

file = open("example.txt", "r")

content = file.read()
print(content)

file.seek(0) # Move the cursor back to the start


line = file.readline()
print(line)

file.seek(0)
lines = file.readlines()
print(lines)

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 9 / 42


Writing to a File

The write() method writes a string to the file.

The writelines() method writes a list of strings to the file.

file = open("example.txt", "w")

file.write("Hello, World!\n")

lines = ["This is the first line.\n",


"This is the second line.\n"]
file.writelines(lines)

file.close()
Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 10 / 42
Appending to a File

The a mode is used to append to a file.

Data is added to the end of the file without deleting its contents.

file = open("example.txt", "a")

file.write("This line will be added to the file.\n")

file.close()

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 11 / 42


Closing a File

After working with a file, it is important to close it to free up system


resources.

The close() method is used to close an opened file.

Closing a file ensures that any changes made to the file are saved
properly.

It is a good practice to always close a file when it is no longer needed.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 12 / 42


Working with File Paths

The os module provides functions for interacting with the operating


system.

import os

cwd = os.getcwd()
print(cwd)

full_path = os.path.join(cwd, "example.txt")


print(full_path)

print(os.path.exists(full_path))

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 13 / 42


Using with Statement

The with statement is used for resource management.

It ensures that the file is properly closed after its suite finishes.

with open("example.txt", "r") as file:


content = file.read()
print(content)

# No need to explicitly close the file

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 14 / 42


Pickling

Pickling is the process of converting a Python object into a byte


stream.

It is used for serializing and deserializing Python objects.

The pickle module is used to perform pickling and unpickling.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 15 / 42


Example of Pickling and Unpickling

import pickle

data = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# Pickling the data


with open('data.pkl', 'wb') as file:
pickle.dump(data, file)

# Unpickling the data


with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)
print(loaded_data)

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 16 / 42


Introduction to Exception Handling

Exception Handling allows you to handle errors gracefully.

It helps to maintain the normal flow of the program even after an error
occurs.

The try, except, else, and finally blocks are used for handling
exceptions.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 17 / 42


Example of Exception Handling

try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
# Code to execute if no exception occurs
print("Division successful")
finally:
# executes whether an exception occurs or not
print("Execution completed")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 18 / 42


Exception Handling When Opening Files

try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found. Please check the file name and
except IOError:
print("An error occurred while reading the file.")
else:
# Code to execute if no exception occurs
print("File read successfully")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 19 / 42


Object Oriented Programming

Object Oriented
Programming

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 20 / 42


Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm


based on the concept of ”objects”.

Objects are instances of classes, which can contain data and code.

OOP aims to implement real-world entities like inheritance, polymor-


phism, encapsulation, and abstraction.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 21 / 42


Benefits of OOP: Modularity and Code Reusability

Modularity:

OOP allows to break down complex problems into smaller, man-


ageable pieces (classes).

Each class can be developed, tested, and debugged independently.

Code Reusability:

Through inheritance, existing code can be reused.

Polymorphism allows for flexibility and interchangeability of com-


ponents.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 22 / 42


Benefits of OOP: Extensibility and Maintainability

Extensibility:

Existing code can be extended by creating new classes.

You can add new functionalities without altering existing code.

Maintainability:

OOP improves maintainability due to its clear structure.

Classes and objects can be easily updated or replaced without


affecting the overall system.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 23 / 42


Benefits of OOP: Encapsulation

Encapsulation:

OOP encapsulates data and functions that operate on the data


within objects.

It provides a clear interface and hides the internal implementation,


enhancing security and reducing complexity.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 24 / 42


Class

A Class is a blueprint for creating objects.

It defines a set of attributes (data) and methods (functions) that the


created objects will have.

Classes help to encapsulate data and functions together into a single


unit.

Classes allow for the creation of multiple objects that share the same
structure and behavior.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 25 / 42


Example: Defining a Simple Class

Here is a simple example of defining a class in Python:

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
return f"{self.name} says woof!"

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 26 / 42


Methods and Attributes

A class can have functions called methods and variables called at-
tributes.

Methods define the behavior of the class.

Attributes hold the data that defines the state of the class.

class Dog:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute

def bark(self): # Method


print(f"{self.name} says woof!")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 27 / 42


The init Method

The init method is a special method called a constructor.

It is automatically called when a new object is created from the class.

It initializes the object’s attributes with the provided values.

class Dog:
def __init__(self, name, age):
self.name = name # Initializes name attribute
self.age = age # Initializes age attribute

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 28 / 42


The Role of self

self is used to access variables of the given class.

It must be the first parameter of any method in the class.

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print(f"{self.name} says woof!")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 29 / 42


Object

An Object is an instance of a class.

Objects are created from a class and have the structure and behavior
defined by the class.

Each object can have different attribute values.

Objects are created by calling the class just like we call a function.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 30 / 42


Creating Objects

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print(f"{self.name} says woof!")

# Creating objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 31 / 42


Accessing Attributes and Methods

You can access an object’s attributes and methods using the dot nota-
tion.

# Accessing attributes
print(dog1.name) # Output: Buddy
print(dog2.age) # Output: 5

# Calling methods
dog1.bark() # Output: Buddy says woof!
dog2.bark() # Output: Lucy says woof!

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 32 / 42


Modifying Object Attributes

Object attributes can be modified directly.

# Modifying attributes
dog1.age = 4
print(dog1.age) # Output: 4

# Adding a new attribute


dog1.breed = "Labrador"
print(dog1.breed) # Output: Labrador

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 33 / 42


Encapsulation and Abstraction

Encapsulation: Bundling data and methods within a class. Restricts


direct access to some of the object’s components.

Abstraction: Hiding complex implementation details and showing only


the essential features of the object.

Private attributes (prefixed with ) are not directly accessible.

Public methods (like bark()) provide controlled access to private at-


tributes.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 34 / 42


Introduction to Inheritance

Inheritance allows a class to inherit attributes and methods from an-


other class.

The class that inherits is called the derived class or subclass.

The class being inherited from is called the base class or superclass.

Inheritance promotes code reuse and establishes a relationship between


classes.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 35 / 42


Base Class and Derived Class

class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def bark(self):
print("Dog barks")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 36 / 42


Creating an Object of the Derived Class

Create an object of the derived class and call the methods to demon-
strate inheritance:

# Creating an object of Dog


dog = Dog()

# Calling methods from both the base and derived class


dog.speak() # Output: Animal speaks
dog.bark() # Output: Dog barks

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 37 / 42


Introduction to Polymorphism

Polymorphism means ”many forms” and it allows objects of different


classes to be treated as objects of a common superclass.

It is achieved through method overriding and interfaces.

Polymorphism allows for flexibility and the ability to define one interface
and have multiple implementations.

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 38 / 42


Example of Polymorphism: Base Class

Define a base class with a method that can be overridden:

class Animal:
def speak(self):
print("Animal speaks")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 39 / 42


Example of Polymorphism: Derived Classes

Define derived classes that override the method from the base class:

class Dog(Animal):
def speak(self):
print("Dog barks")

class Cat(Animal):
def speak(self):
print("Cat meows")

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 40 / 42


Demonstrating Polymorphism

Create objects of the derived classes and demonstrate polymorphism


by calling the overridden methods:

# Creating objects
dog = Dog()
cat = Cat()

# Demonstrating polymorphism
dog.speak() # Output: Dog barks
cat.speak() # Output: Cat meows

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 41 / 42


END

Thank You!!!

Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 42 / 42

You might also like