1. OOP Concepts
Classes are blueprints, objects are instances
Class
A blueprint for creating objects
class Dog:
pass
Object
An instance of a class
my_dog = Dog()
Attribute
Data associated with an object
my_dog.name = "Rover"
Method
Function associated with an object
def bark(self):
print("Woof!")
2. Defining Classes
Basic Class Structure
class Car:
# Class attribute (shared by all instances)
wheels = 4
# Constructor (initialize instance attributes)
def __init__(self, brand, model):
self.brand = brand # Instance attribute
self.model = model
# Instance method
def description(self):
return f"{self.brand} {self.model}"
# Create objects
my_car = Car("Toyota", "Corolla")
print(my_car.description()) # Toyota Corolla
Exercise 1: Create a Book Class
Create a Book class with:
- Attributes:
title,author,pages - Method
info()that returns a description - Create an instance and call the method
3. Inheritance
Base (Parent) Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement")
Derived (Child) Class
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy says Woof!
print(cat.speak()) # Whiskers says Meow!
Exercise 2: Shape Inheritance
Create a base Shape class with:
- Method
area()that raisesNotImplementedError - Derived classes
RectangleandCircle - Implement
area()in each subclass
4. Encapsulation
Private Attributes (Name Mangling)
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
# account.__balance # Error: AttributeError
Python doesn't have truly private attributes, but name mangling (__attribute) makes them harder to access accidentally.
5. Polymorphism
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def animal_sound(animal):
print(animal.speak())
dog = Dog()
cat = Cat()
animal_sound(dog) # Woof!
animal_sound(cat) # Meow!
Exercise 3: Polymorphic Payment
Create payment classes that demonstrate polymorphism:
- Base class
Paymentwithprocess()method - Subclasses
CreditCard,PayPal,BankTransfer - Each implements
process()differently