Python 3 Deep Dive Part 4 Oop 【iOS】

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of objects and classes. In OOP, a program is designed as a collection of objects that interact with each other to achieve a specific goal. Each object represents a real-world entity, such as a car, a person, or a bank account, and has its own set of attributes (data) and methods (functions).

In Python 3, super() is often called without arguments. It is actually a proxy object that delegates method calls to the next class in the MRO.

Crucial Insight: super() does not refer strictly to the parent class. It refers to the next class in the linearization chain of the instance. python 3 deep dive part 4 oop

This allows for Cooperative Multiple Inheritance. Every method in the hierarchy should call super() to ensure the next link in the chain executes.

class A:
    def process(self):
        print("A process")
        super().process() # Crucial: A doesn't know who calls next, but it passes the baton.
class B(A):
    def process(self):
        print("B process")
        super().process()
class C(A):
    def process(self):
        print("C process")
        # End of the chain for this specific logic
class D(B, C):
    def process(self):
        print("D process")
        super().process()
d = D()
d.process()
# Output:
# D process
# B process
# C process
# Note: A.process() is NOT called here because C did not call super().
# If C called super(), A would run.

Descriptors are reusable attribute logic. They are Python objects that define __get__, __set__, or __delete__. Used for @property, @staticmethod, @classmethod. Descriptors are reusable attribute logic

class PositiveNumber:
    def __set_name__(self, owner, name):
        self.name = name
def __get__(self, obj, objtype=None):
    return obj.__dict__.get(self.name)
def __set__(self, obj, value):
    if value <= 0:
        raise ValueError(f"self.name must be positive")
    obj.__dict__[self.name] = value

class Order: quantity = PositiveNumber() price = PositiveNumber()

def __init__(self, quantity, price):
    self.quantity = quantity
    self.price = price

class Singleton:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance
class Multiplier:
    def __init__(self, factor):
        self.factor = factor
    def __call__(self, x):
        return x * self.factor

double = Multiplier(2) print(double(5)) # 10 model real-world objects


Welcome to the fourth installment of our Python 3 Deep Dive series, where we explore the depths of the Python programming language. In this article, we'll dive into the world of Object-Oriented Programming (OOP) in Python 3. OOP is a fundamental concept in programming that allows you to create reusable code, model real-world objects, and write more maintainable and efficient software.