Classes and Objects
class Dog:
species = "Canis familiaris"
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
def bark(self):
return f"{self.name} says Woof!"
def __str__(self):
return f"{self.name} ({self.breed}, {self.age})"
rex = Dog("Rex", 5, "German Shepherd")
print(rex.bark()) # Rex says Woof!
Inheritance
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}!"
class Cat(Animal):
def __init__(self, name, indoor=True):
super().__init__(name, "Meow")
self.indoor = indoor
def purr(self):
return f"{self.name} purrs..."
cat = Cat("Whiskers")
print(cat.speak()) # Whiskers says Meow!
print(cat.purr()) # Whiskers purrs...
Polymorphism
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
shapes = [Circle(5), Rectangle(4, 6)]
for s in shapes:
print(f"{s.__class__.__name__}: {s.area():.2f}")
Properties and Encapsulation
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Must be positive")
self._balance += amount
return self._balance
Ready to Level Up Your Coding Skills?
Join Coderz Club and learn to code with challenges, battles, and an AI mentor.
Join Coderz Club Free →