Python Advanced Notes
Object-Oriented Programming
Python supports OOP to model real-world things using classes and objects.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
return f"{self.brand} {self.model} is driving"
mycar = Car("Tesla", "Model S")
print(mycar.drive())
Inheritance and Polymorphism
Inheritance allows one class to use methods/attributes of another.
Example:
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
dog = Dog()
print(dog.sound()) # Bark
Modules and Packages
Modules are Python files with reusable code. Packages are collections of modules.
Example:
import math
print(math.sqrt(16))
Error and Exception Handling
Errors stop programs. Exceptions handle them gracefully.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
Iterators and Generators
Iterators are objects that can be looped. Generators use 'yield' to create iterators.
Example:
def gen_numbers():
for i in range(5):
yield i
for num in gen_numbers():
print(num)
Decorators
Decorators modify the behavior of functions.
Example:
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator
def say_hello():
print("Hello")
say_hello()
Lambda Functions and Comprehensions
Lambda functions are small anonymous functions.
Example: square = lambda x: x*x
print(square(4))
List comprehension makes lists in one line:
nums = [x**2 for x in range(5)]
Virtual Environment and pip
A virtual environment isolates project dependencies.
Commands:
python -m venv myenv
myenv\Scripts\activate (Windows)
source myenv/bin/activate (Linux/Mac)
Use pip to install libraries:
pip install numpy