Object-Oriented Programming
Section 4: Object-Oriented Programming (OOP)
Lesson 1: Introduction to OOP in Python
1.1 Classes and Objects
Object-Oriented Programming (OOP) is a paradigm that revolves around the concept of classes and objects. A class is a blueprint for creating objects, and objects are instances of classes.
Example:
# Class definition
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
# Creating objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
# Accessing object attributes and methods
print(dog1.name) # Output: Buddy
dog2.bark() # Output: Woof!
1.2 Inheritance, Encapsulation, and Polymorphism
Inheritance: Allows a class (subclass) to inherit properties and methods from another class (superclass).
Example:
# Inheritance
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
class GraduateStudent(Student):
def __init__(self, name, age, program):
super().__init__(name, age)
self.program = program
grad_student = GraduateStudent("Alice", 25, "Computer Science")
print(grad_student.name) # Output: Alice
Encapsulation: Restricts access to certain components of a class and prevents the accidental modification of data.
Example:
# Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
account = BankAccount(1000)
print(account.get_balance()) # Output: 1000
Polymorphism: Enables a single interface to represent different types. In Python, it often involves method overloading or overriding.
Example:
# Polymorphism
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
circle = Circle(5)
square = Square(4)
print(circle.area()) # Output: 78.5
print(square.area()) # Output: 16
Lesson 2: File Handling
2.1 Reading and Writing to Files
File handling is essential for reading from and writing to files. Python provides built-in functions for these operations.
Example:
# Reading and writing to files
with open("example.txt", "w") as file:
file.write("Hello, Python!")
with open("example.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, Python!
2.2 Working with Different File Formats (txt, csv)
Python supports various file formats. Working with CSV files, for instance, involves using the csv module.
Example:
# Working with CSV files
import csv
data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "San Francisco"]
]
with open("data.csv", "w", newline="") as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerows(data)
with open("data.csv", "r") as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
print(row)
# Output:
# ['Name', 'Age', 'City']
# ['Alice', '25', 'New York']
# ['Bob', '30', 'San Francisco']
In Section 4, we delved into Object-Oriented Programming (OOP) in Python, introducing the concepts of classes, objects, inheritance, encapsulation, and polymorphism. OOP provides a powerful paradigm for structuring code and creating reusable, maintainable software.
Additionally, we explored file handling in Python, covering the basics of reading from and writing to files. Working with different file formats, such as text (txt) and comma-separated values (csv), allows for efficient data storage and retrieval.
As you incorporate OOP principles and file handling into your Python projects, you'll gain the ability to design more modular, scalable, and organized code. These concepts form a solid foundation for building complex and robust applications in Python.