Welcome to the Advanced Object-Oriented Programming (OOP) tutorial! In this guide, we'll dive deeper into the concepts of OOP, including inheritance, polymorphism, and encapsulation.

Inheritance

Inheritance is a fundamental concept in OOP that allows one class to inherit properties and methods from another class. This concept is often referred to as "IS-A" relationship. For example, a Dog class can inherit from a Mammal class.

class Mammal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Mammal sound"

class Dog(Mammal):
    def speak(self):
        return "Woof!"

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. This is often used in method overriding. For instance, the speak method in the Dog class overrides the speak method in the Mammal class.

mammal = Mammal("Generic Mammal")
dog = Dog("Buddy")

print(mammal.speak())  # Output: Mammal sound
print(dog.speak())    # Output: Woof!

Encapsulation

Encapsulation is the concept of hiding the internal state of an object and requiring all interaction to be performed through an object's methods. This helps to protect the integrity of the object.

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

    def deposit(self, amount):
        self._balance += amount

    def withdraw(self, amount):
        if self._balance >= amount:
            self._balance -= amount
        else:
            print("Insufficient funds")

    def get_balance(self):
        return self._balance

Bank Account Diagram

For more information on OOP concepts, check out our Basic OOP Tutorial.