Advanced·22 min·0/52 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"))

Your turn · answer checked automatically

Exercise

Create a class MedianRegressor that inherits from Estimator. Its fit(X, y) stores the median of y in self.median_ and returns self. Its predict(X) returns that median once per row of X.

Edit the code, then press Run & check. Passing it marks this lesson done.

python console

Exercise

~/lesson.py

Ctrl+Enter

console output

ready

$ waiting for Run...

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.