Chapter 6 Python
Chapter 6 Python
Eyob S.
SITE, AAiT
July 2, 2024
1 Persistence
Persistence
Data stored in variables and data structures is temporary and lost when
the program terminates.
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().
The open() function is used to open a file and return a file object.
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:
'w' - Opens the file for writing (creates a new file or truncates an
existing file).
'b' - Binary mode. Used in combination with other modes (e.g., 'rb',
'wb').
content = file.read()
print(content)
file.seek(0)
lines = file.readlines()
print(lines)
file.write("Hello, World!\n")
file.close()
Eyob S. (SITE, AAiT) Computer Programming July 2, 2024 10 / 42
Appending to a File
Data is added to the end of the file without deleting its contents.
file.close()
Closing a file ensures that any changes made to the file are saved
properly.
import os
cwd = os.getcwd()
print(cwd)
print(os.path.exists(full_path))
It ensures that the file is properly closed after its suite finishes.
import pickle
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.
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")
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")
Object Oriented
Programming
Objects are instances of classes, which can contain data and code.
Modularity:
Code Reusability:
Extensibility:
Maintainability:
Encapsulation:
Classes allow for the creation of multiple objects that share the same
structure and behavior.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
A class can have functions called methods and variables called at-
tributes.
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
class Dog:
def __init__(self, name, age):
self.name = name # Initializes name attribute
self.age = age # Initializes age attribute
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
Objects are created from a class and have the structure and behavior
defined by the class.
Objects are created by calling the class just like we call a function.
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)
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!
# Modifying attributes
dog1.age = 4
print(dog1.age) # Output: 4
The class being inherited from is called the base class or superclass.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
Create an object of the derived class and call the methods to demon-
strate inheritance:
Polymorphism allows for flexibility and the ability to define one interface
and have multiple implementations.
class Animal:
def speak(self):
print("Animal speaks")
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")
# Creating objects
dog = Dog()
cat = Cat()
# Demonstrating polymorphism
dog.speak() # Output: Dog barks
cat.speak() # Output: Cat meows
Thank You!!!