Object-Oriented Programming
Understand classes, objects, inheritance, and encapsulation in Python.
Classes and Objects
OOP is a paradigm based on "objects", which can contain data (attributes) and code (methods).
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark()
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
my_dog.bark()
Inheritance
Classes can inherit from other classes to reuse and extend code.
class Animal:
def speak(self):
pass
class Cat(Animal):
def speak(self):
print("Meow!")
my_cat = Cat()
my_cat.speak()
def speak(self):
pass
class Cat(Animal):
def speak(self):
print("Meow!")
my_cat = Cat()
my_cat.speak()
Encapsulation and Properties
Control access to internal state using private attributes (prefixed with _ or __) and properties.
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
acc = Account(1000)
print(acc.balance)
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
acc = Account(1000)
print(acc.balance)
โ Practice (20 minutes)
- Create a
Carclass with attributesmake,model, andyear. - Add a
drive()method that prints"The [make] [model] is driving." - Create an
ElectricCarclass that inherits fromCarand adds abattery_sizeattribute. - Override the
drive()method inElectricCarto include battery information.