All categories

    OOP

    Classes, inheritance, and special methods.

    01Define a class

    main.py
    class Dog:
        def __init__(self, name):
            self.name = name
    
        def bark(self):
            return f"{self.name} says woof!"
    
    d = Dog("Rex")
    print(d.bark())
    Output
    Rex says woof!

    02Inheritance

    main.py
    class Animal:
        def speak(self):
            return "..."
    
    class Cat(Animal):
        def speak(self):
            return "Meow"
    
    print(Cat().speak())
    Output
    Meow

    03Class and instance attributes

    main.py
    class Counter:
        count = 0
    
        def __init__(self):
            Counter.count += 1
    
    a = Counter()
    b = Counter()
    c = Counter()
    print(Counter.count)
    Output
    3

    04__str__ and __repr__

    main.py
    class Point:
        def __init__(self, x, y):
            self.x, self.y = x, y
        def __str__(self):
            return f"({self.x}, {self.y})"
    
    p = Point(3, 4)
    print(p)
    Output
    (3, 4)

    05Static and class methods

    main.py
    class Math:
        @staticmethod
        def add(a, b):
            return a + b
    
        @classmethod
        def name(cls):
            return cls.__name__
    
    print(Math.add(3, 4))
    print(Math.name())
    Output
    7
    Math