Skip to content

    Object-Oriented Programming in Python

    Python · Intermediate

    Definition

    OOP organises code into classes (blueprints) and objects (instances) with attributes and methods.

    OOP models real-world entities and is used in most large Python projects.

    Diagram

    Class Animal→ Dog(Animal)→ Cat(Animal)objects: rex, tom

    Flowchart

    Define class__init__ sets attributesAdd methodsCreate objectsInherit to extend

    Example: Inheritance

    class Animal:
        def speak(self): return '...'
    class Dog(Animal):
        def speak(self): return 'Woof'
    print(Dog().speak())

    Output: Woof

    Key points

    • Encapsulation, inheritance, polymorphism, abstraction
    • self refers to the instance
    • Dunder methods customise behaviour

    Interview questions

    What is polymorphism?

    Different classes responding to the same method call in their own way.

    @staticmethod vs @classmethod?

    classmethod receives the class (cls); staticmethod receives neither.

    More Python topics