Introduction
Object-Oriented Programming (OOP) organizes code around objects that combine data and functionality.
Classes and Objects
class Dog:
# Class attribute
species = "Canis familiaris"
# Constructor
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age
# Instance method
def bark(self):
return f"{self.name} says woof!"
# String representation
def __str__(self):
return f"{self.name} is {self.age} years old"
# Create object
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Cat(Animal):
def speak(self):
return f"{self.name} says meow"
class Dog(Animal):
def speak(self):
return f"{self.name} says woof"
Multiple Inheritance
class Flyable:
def fly(self):
return f"{self.name} is flying"
class Swimmable:
def swim(self):
return f"{self.name} is swimming"
class Duck(Animal, Flyable, Swimmable):
pass
Practice Problems
- Create a BankAccount class with deposit/withdraw
- Design an inheritance hierarchy for shapes
- Implement str and repr methods
- Create a class with class and instance attributes
- Use multiple inheritance for a real scenario