5. Object-Oriented Programming (OOP)
1. Classes and Objects
python
class Person:
def __init__(self, name, age): # Constructor
self.name = name
self.age = age
def say_hello(self): # Instance method
print(f”Hello, I’m {self.name}, {self.age} years old.”)
p = Person(“Alice”, 25) # Create an object
p.say_hello() # Call method
2. Inheritance: A subclass inherits properties and methods from a superclass.
python
class Student(Person): # Student inherits from Person
def __init__(self, name, age, student_id):
super().__init__(name, age) # Call superclass constructor
self.student_id = student_id
6. Modules and Packages
– Importing Modules:
python
import math # Import the entire module
print(math.sqrt(16)) # Output 4.0
from math import sqrt # Import specific function from module
print(sqrt(25)) # Output 5.0
– Custom Modules: Save code as a .py file (e.g., my_module.py) and import it using import my_module.
7. File Operations
– Reading and Writing Files:
python
# Writing to a file (‘w’ mode overwrites, ‘a’ appends)
with open(‘data.txt’, ‘w’, encoding=’utf-8′) as f:
f.write(‘Hello, Python!\n’)
# Reading from a file
with open(‘data.txt’, ‘r’, encoding=’utf-8′) as f:
content = f.read()
print(content)
– File Modes: r (read), w (write), a (append), b (binary mode).