Advanced·22 min·0/47 done

Python Inheritance

Subclassing, duck typing, abstract base classes, and special methods.

Why it matters: Custom models, tools, and estimators share interfaces like fit/predict or search.

Basics

Inheritance and super()

class Child(Parent): inherits attributes and methods.

Override a method by redefining it. Call super().method() to extend the parent.

Always call super().__init__(...) in subclass constructors. Keep hierarchies shallow.

Tiny example

Subclass calls super().__init__ then stores extra state.

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

class Child(Base):
    def __init__(self, name, k):
        super().__init__(name)
        self.k = k

print(Child("rag", 3).name)

Basics

Duck Typing

If an object has the method you need, it works. No shared base class is required.

That is duck typing. Pipelines only care about .search(query) or .predict(X).

Use abc.ABC with @abstractmethod when you want Python to enforce the contract.

Tiny example

Call the same method name on two different objects.

class A:
    def search(self, q):
        return ["a:" + q]

class B:
    def search(self, q):
        return ["b:" + q]

print(A().search("x"), B().search("x"))

Basics

Dunder Methods

Special methods hook into Python syntax:

  • __repr__ - debug print
  • __len__ - len(obj)
  • __getitem__ - obj[i]
  • __call__ - obj(...)

@property turns a method into a read-only attribute like budget.remaining.

Tiny example

Implement __len__ so len(obj) works.

class Chunks:
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)

print(len(Chunks(["a", "b"])))

Then AI / ML

AI / ML examples

Same idea, used in real AI work. Press Try in lab to run it.

AI / ML example

AI / ML: shared search interface

The pipeline only needs .search().

In AI / ML: You can swap a vector store for a keyword store if both expose search.

example.py

Python

class VectorStore:
    def search(self, query):
        return [f"vector:{query}"]

class SqlStore:
    def search(self, query):
        return [f"sql:{query}"]

for store in [VectorStore(), SqlStore()]:
    print(store.search("mlops"))

AI / ML example 2

AI / ML: abstract retriever base

Incomplete subclasses fail at construction time.

In AI / ML: Retriever bases force search() to exist before you deploy.

example.py

Python

from abc import ABC, abstractmethod

class BaseRetriever(ABC):
    @abstractmethod
    def search(self, query):
        pass

class EchoRetriever(BaseRetriever):
    def search(self, query):
        return [query]

print(EchoRetriever().search("rag"))

Takeaways

  • 1Always call super().__init__() in a subclass constructor.
  • 2Duck typing means any object with the right method works.
  • 3Define __repr__ and use @property for computed attributes.
Certificate