Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

Inheritance: a class built on another

Agent frameworks often hand you a base class and ask you to write one method. That is inheritance: a new class that starts with everything another has.

Here is a base class for any model. It knows how to answer a list of texts, but not how to answer one:

Example
class Model:
    def ask(self, text):
        raise NotImplementedError("a model must say how it answers")

    def ask_all(self, texts):
        return [self.ask(text) for text in texts]

Model().ask("refund please")

ask_all calls self.ask for each text. ask itself only raises NotImplementedError, Python's standard way to say that a subclass must fill this in.

Filling in the one method

Example
class KeywordModel(Model):
    def ask(self, text):
        if "refund" in text.lower() or "charged" in text.lower():
            return '{"category": "billing", "priority": 4}'
        return '{"category": "other", "priority": 1}'

model = KeywordModel()
print(model.ask("Can I get a refund?"))
print(model.ask_all(["I was charged twice", "Hello"]))

class KeywordModel(Model) means KeywordModel inherits from Model. It gets ask_all without writing it, and its own ask replaces the one that raised. When ask_all calls self.ask, self is a KeywordModel, so the new version runs.

This is the pattern behind every stand-in model you will write in the framework courses: subclass the framework's model class, write the method that produces an answer, and the framework's code does the rest.

Keeping the parent's __init__

Example
class Model:
    def __init__(self, name):
        self.name = name

class KeywordModel(Model):
    def __init__(self, keywords):
        super().__init__(name="keywords")
        self.keywords = keywords

model = KeywordModel(["refund", "charged"])
print(model.name, model.keywords)
print(isinstance(model, Model))

A subclass with its own __init__ replaces the parent's, so name would never be set. super().__init__(...) runs the parent's version too. isinstance confirms a KeywordModel counts as a Model, which is what lets framework code accept it.

Try it yourself
  • Remove the super().__init__ line and print model.name.
  • Write a second subclass, PoliteModel, whose ask always returns "Thank you for your message.", and call ask_all on it.
  • Give KeywordModel's ask a "parcel" branch that returns shipping.

You understood something today that you didn't yesterday.