Introduction
Object-oriented programming (OOP) is a paradigm that organizes code into classes (blueprints) and objects (instances). Python is a fully object-oriented language — in fact, everything in Python is an object.
Creating classes
class Dog:
# Class variable (shared by all instances)
species = "Canis familiaris"
def __init__(self, name, age):
# Instance variables (unique to each instance)
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
def __str__(self):
return f"{self.name}, age {self.age}"
def __repr__(self):
return f"Dog('{self.name}', {self.age})"
# Creating objects
my_dog = Dog("Rex", 3)
print(my_dog.bark()) # "Rex says Woof!"
print(my_dog) # "Rex, age 3" (uses __str__)
print(my_dog.species) # "Canis familiaris"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!"
animals = [Cat("Whiskers"), Dog("Buddy")]
for animal in animals:
print(animal.speak()) # Polymorphism in action!Assignment
- Read about Python classes in the official tutorial.
- Create a
BankAccountclass with deposit, withdraw, and balance methods. - Create a
SavingsAccountthat inherits fromBankAccountand adds an interest rate.