Alternative constructors for chat messages
AI code constantly turns dictionaries from JSON into objects. Note that LoudMessage.from_dict returns a LoudMessage because it uses cls. The line super().__init__(...) in LoudMessage runs the parent class's setup; Topic 8.5 teaches it.
Python has three kinds of method. An instance method works on one object (self), a class method works on the class itself (cls) and is the standard way to write alternative constructors, and a static method is a plain function that lives inside a class for organisation.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Temperature with attribute celsius, an instance method to_fahrenheit(), a class method from_fahrenheit(f) that builds one, and a static method is_freezing(c) that is true when c <= 0.
Write a class User with name and email, and a class method from_dict(data). Build a user from {"name": "Asha", "email": "a@x.com"} and print both attributes.
Make a subclass Admin(User) and show that Admin.from_dict(...) returns an Admin. Print the class name.
Explain it without notes
What is the difference between an instance method, a class method and a static method?
Why write return cls(...) in a class method instead of return ClassName(...)?
What is an alternative constructor, and why does Python use class methods for them?
What is a bound method?
Expected output
Message('user', 'Hello')
Message('assistant', 'Hi there')
LoudMessage('assistant', 'HI THERE')
LoudMessage
{"role": "user", "content": "Hello"}