PyForge ยท Python practice library
All topics

Topic 10 of 17

Object-Oriented Programming

Classes, objects, inheritance, polymorphism, and encapsulation in Python.

class & __init__
Instance vs class attrs
Inheritance
super()
dunder methods

Basic

1 program

Program 1

Define a class

Basic

Create a class with an initializer.

python
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return f"{self.name} says Woof!"

d = Dog("Rex", "Labrador")
print(d.bark())

Intermediate

2 programs

Program 1

Inheritance

Intermediate

Extend a base class with super().

python
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "Some sound"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow"

print(Cat("Luna").speak())

Program 2

Encapsulation with property

Intermediate

Validate input through setters.

python
class Account:
    def __init__(self, balance=0):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("Negative balance not allowed")
        self._balance = value

a = Account(100)
a.balance = 250
print(a.balance)

Advanced

2 programs

Program 1

Dunder methods

Advanced

Customize built-in behavior.

python
class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

print(Vector(1, 2) + Vector(3, 4))

Program 2

Abstract base class

Advanced

Force subclasses to implement methods.

python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        ...

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14159 * self.r ** 2

print(Circle(5).area())