{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"classes-and-objects","title":"Classes: when a dict stops being enough","url":"https://addaly.com/learn/python-for-ai/classes-and-objects","position":60,"of":89,"minutes":9,"answer":"A class bundles data with the functions that act on it and gives the bundle a name; self is simply the object the method was called on.","keyIdea":"A class bundles data with the functions that act on it and gives the bundle a name; self is simply the object the method was called on, and a mutable value placed on the class rather than in __init__ is shared by every instance."},"body":{"format":"markdown","text":"## The dict that grew\n\nYou have been representing a conversation as a list of dicts, which works. Then you need to know its total token count, trim it when it gets long, save it, and reload it. Each of those is a function that takes the list, and the functions start to need each other, and you find yourself passing around a list, a token count, a model name and a file path together, always together. That is the signal. Data that always travels with the same functions wants to be an object.\n\n```python\nclass Conversation:\n    def __init__(self, model, system=None):\n        self.model = model\n        self.messages = []\n        if system:\n            self.messages.append(\n                {\"role\": \"system\", \"content\": system}\n            )\n\n    def add(self, role, text):\n        self.messages.append(\n            {\"role\": role, \"content\": text}\n        )\n\n    def last(self):\n        return (\n            self.messages[-1][\"content\"]\n            if self.messages\n            else None\n        )\n\n    def __repr__(self):\n        return (\n            f\"Conversation(model={self.model!r}, \"\n            f\"turns={len(self.messages)})\"\n        )\n```\n\n```python\nc = Conversation(\"gpt-4o-mini\", system=\"Be brief.\")\nc.add(\"user\", \"What is a class?\")\nprint(c)                      # Conversation(model='gpt-4o-mini', turns=2)\nprint(c.last())\n```\n\n## What each piece is\n\n`class Conversation:` defines a new type, exactly as `int` and `list` are types. `Conversation(\"gpt-4o-mini\")` creates an **instance** (an object of that type) and Python calls `__init__` on it with the arguments you passed.\n\n`self` is the instance. It is not a keyword; it is a naming convention so strong that breaking it is rude. When you write `c.add(\"user\", \"hi\")`, Python turns it into `Conversation.add(c, \"user\", \"hi\")`. That is the entire mystery of `self`: it is the object before the dot, passed as the first argument.\n\n`self.model = model` creates an **attribute** on that instance. Each instance has its own set; `c.model` and `d.model` are separate slots.\n\n`__repr__` decides what `print(c)` and the shell show. Without it you get `<__main__.Conversation object at 0x104f3e2d0>`, which is useless. Write it on every class you will debug, which is every class.\n\n## The trap in the class body\n\nThis looks equivalent and is not:\n\n```python\nclass Conversation:\n    messages = []             # one list, on the class\n\n    def add(self, role, text):\n        self.messages.append({\"role\": role, \"content\": text})\n```\n\n`messages = []` runs once, when the class is defined, and creates one list that belongs to the class. `self.messages` looks for an attribute on the instance, does not find one, and falls through to the class, where it finds the shared list. Every instance appends to the same list. Two conversations become one.\n\nA value assigned in the class body is a **class attribute**, shared by all instances. A value assigned to `self.something` in `__init__` is an **instance attribute**, one per object. Constants belong on the class; anything mutable belongs in `__init__`. This is the same lesson as the mutable default argument from module 3, wearing a different coat.\n\n## Methods that do not need an instance\n\nSometimes a function belongs with the class but not with any particular object:\n\n```python\nclass Conversation:\n    ...\n    @classmethod\n    def from_file(cls, path):\n        data = json.loads(Path(path).read_text())\n        conv = cls(data[\"model\"])\n        conv.messages = data[\"messages\"]\n        return conv\n```\n\n`Conversation.from_file(\"chat.json\")` builds an instance from saved data. `cls` is the class itself, so this still works if someone subclasses `Conversation` later. Alternative constructors are the usual reason for a `@classmethod`.\n\n## Attributes are not private\n\nNothing stops `c.messages = \"oops\"`. Python has no `private` keyword. The convention is a leading underscore: `self._cache` means \"not part of the interface; touch it and you own the consequences\". It is a message to readers, not a lock. Most of the time that is enough.\n\nWhen you need to compute a value on access, or validate on assignment, `@property` makes a method look like an attribute:\n\n```python\n    @property\n    def turns(self):\n        return sum(\n            1\n            for m in self.messages\n            if m[\"role\"] != \"system\"\n        )\n```\n\n`c.turns` (no brackets) calls the method. Use it for cheap derived values. A property that makes a network call is a trap for whoever reads `c.turns` in a loop.\n\n## When not to write a class\n\nA class is not a badge of seriousness. If a dict does the job and no functions cluster around it, keep the dict. If you have a function and some fixed settings, a function with default arguments or a closure is simpler than a class with one method. Classes earn their place when data and behaviour belong together, or when you need several objects of the same shape that carry their own state: one `Conversation` per user, one `Budget` per job.\n\nThe `Budget` class from the previous module is the pattern at its smallest: two numbers and the one method that changes them, kept together so that nobody updates one without the other.\n\n## Try this now\n\nWrite `Conversation` with `add`, `last`, `__repr__`, and a `token_estimate` method that sums `len(content) // 4` across messages. Then rewrite it with `messages = []` in the class body, create two instances, and watch them share. Put it back."},"check":{"question":"A developer writes `class Conversation:` with `messages = []` declared directly in the class body, and an `add(self, role, text)` method that appends to `self.messages`. They create two conversations, add a message to the first, and find the second conversation contains it too. Why?","options":[{"text":"`append` on a list inside a method always modifies the most recently created instance rather than `self`.","correct":false,"tempting":"Methods act on whichever object they were called on; there is no notion of most recent."},{"text":"Two instances of the same class share memory until one of them is modified, at which point Python copies the object, and the copy happened only after the append had already been applied to both.","correct":false,"tempting":"Python has no copy-on-write for instances; each object has its own attribute dictionary from the moment it is created."},{"text":"The `add` method is missing a `return`, so the appended list is discarded and the class-level list is used as a fallback.","correct":false,"tempting":"`append` mutates in place and returns nothing whatever the method returns; the fallback described does not exist."},{"text":"`messages = []` in the class body makes one list on the class, and `self.messages` falls through to it because no instance got its own in `__init__`.","correct":true}]},"prev":{"slug":"counting-tokens-and-cost","title":"Knowing what each call cost: usage figures, token counting, and a budget that stops the program","url":"https://addaly.com/learn/python-for-ai/counting-tokens-and-cost"},"next":{"slug":"dataclasses","title":"Dataclasses: the class that is mostly data, written in four lines","url":"https://addaly.com/learn/python-for-ai/dataclasses"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Classes: when a dict stops being enough', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/classes-and-objects (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Classes: when a dict stops being enough","courseTitle":"Python, from Zero, for AI","module":{"index":7,"slug":"objects-and-the-shape-of-programs","title":"Objects, generators and the shape a larger program takes"},"answer":null,"keyIdea":"A class bundles data with the functions that act on it and gives the bundle a name; self is simply the object the method was called on, and a mutable value placed on the class rather than in __init__ is shared by every instance.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-dict-that-grew","runs":[{"text":"The dict that grew"}]},{"t":"p","runs":[{"text":"You have been representing a conversation as a list of dicts, which works. Then you need to know its total token count, trim it when it gets long, save it, and reload it. Each of those is a function that takes the list, and the functions start to need each other, and you find yourself passing around a list, a token count, a model name and a file path together, always together. That is the signal. Data that always travels with the same functions wants to be an object."}]},{"t":"code","lang":"python","label":"Python","text":"class Conversation:\n    def __init__(self, model, system=None):\n        self.model = model\n        self.messages = []\n        if system:\n            self.messages.append(\n                {\"role\": \"system\", \"content\": system}\n            )\n\n    def add(self, role, text):\n        self.messages.append(\n            {\"role\": role, \"content\": text}\n        )\n\n    def last(self):\n        return (\n            self.messages[-1][\"content\"]\n            if self.messages\n            else None\n        )\n\n    def __repr__(self):\n        return (\n            f\"Conversation(model={self.model!r}, \"\n            f\"turns={len(self.messages)})\"\n        )"},{"t":"code","lang":"python","label":"Python","text":"c = Conversation(\"gpt-4o-mini\", system=\"Be brief.\")\nc.add(\"user\", \"What is a class?\")\nprint(c)                      # Conversation(model='gpt-4o-mini', turns=2)\nprint(c.last())"},{"t":"h2","id":"what-each-piece-is","runs":[{"text":"What each piece is"}]},{"t":"p","runs":[{"text":"class Conversation:","code":true},{"text":" defines a new type, exactly as "},{"text":"int","code":true},{"text":" and "},{"text":"list","code":true},{"text":" are types. "},{"text":"Conversation(\"gpt-4o-mini\")","code":true},{"text":" creates an "},{"text":"instance","b":true},{"text":" (an object of that type) and Python calls "},{"text":"__init__","code":true},{"text":" on it with the arguments you passed."}]},{"t":"p","runs":[{"text":"self","code":true},{"text":" is the instance. It is not a keyword; it is a naming convention so strong that breaking it is rude. When you write "},{"text":"c.add(\"user\", \"hi\")","code":true},{"text":", Python turns it into "},{"text":"Conversation.add(c, \"user\", \"hi\")","code":true},{"text":". That is the entire mystery of "},{"text":"self","code":true},{"text":": it is the object before the dot, passed as the first argument."}]},{"t":"p","runs":[{"text":"self.model = model","code":true},{"text":" creates an "},{"text":"attribute","b":true},{"text":" on that instance. Each instance has its own set; "},{"text":"c.model","code":true},{"text":" and "},{"text":"d.model","code":true},{"text":" are separate slots."}]},{"t":"p","runs":[{"text":"__repr__","code":true},{"text":" decides what "},{"text":"print(c)","code":true},{"text":" and the shell show. Without it you get "},{"text":"<__main__.Conversation object at 0x104f3e2d0>","code":true},{"text":", which is useless. Write it on every class you will debug, which is every class."}]},{"t":"h2","id":"the-trap-in-the-class-body","runs":[{"text":"The trap in the class body"}]},{"t":"p","runs":[{"text":"This looks equivalent and is not:"}]},{"t":"code","lang":"python","label":"Python","text":"class Conversation:\n    messages = []             # one list, on the class\n\n    def add(self, role, text):\n        self.messages.append({\"role\": role, \"content\": text})"},{"t":"p","runs":[{"text":"messages = []","code":true},{"text":" runs once, when the class is defined, and creates one list that belongs to the class. "},{"text":"self.messages","code":true},{"text":" looks for an attribute on the instance, does not find one, and falls through to the class, where it finds the shared list. Every instance appends to the same list. Two conversations become one."}]},{"t":"p","runs":[{"text":"A value assigned in the class body is a "},{"text":"class attribute","b":true},{"text":", shared by all instances. A value assigned to "},{"text":"self.something","code":true},{"text":" in "},{"text":"__init__","code":true},{"text":" is an "},{"text":"instance attribute","b":true},{"text":", one per object. Constants belong on the class; anything mutable belongs in "},{"text":"__init__","code":true},{"text":". This is the same lesson as the mutable default argument from module 3, wearing a different coat."}]},{"t":"h2","id":"methods-that-do-not-need-an-instance","runs":[{"text":"Methods that do not need an instance"}]},{"t":"p","runs":[{"text":"Sometimes a function belongs with the class but not with any particular object:"}]},{"t":"code","lang":"python","label":"Python","text":"class Conversation:\n    ...\n    @classmethod\n    def from_file(cls, path):\n        data = json.loads(Path(path).read_text())\n        conv = cls(data[\"model\"])\n        conv.messages = data[\"messages\"]\n        return conv"},{"t":"p","runs":[{"text":"Conversation.from_file(\"chat.json\")","code":true},{"text":" builds an instance from saved data. "},{"text":"cls","code":true},{"text":" is the class itself, so this still works if someone subclasses "},{"text":"Conversation","code":true},{"text":" later. Alternative constructors are the usual reason for a "},{"text":"@classmethod","code":true},{"text":"."}]},{"t":"h2","id":"attributes-are-not-private","runs":[{"text":"Attributes are not private"}]},{"t":"p","runs":[{"text":"Nothing stops "},{"text":"c.messages = \"oops\"","code":true},{"text":". Python has no "},{"text":"private","code":true},{"text":" keyword. The convention is a leading underscore: "},{"text":"self._cache","code":true},{"text":" means “not part of the interface; touch it and you own the consequences”. It is a message to readers, not a lock. Most of the time that is enough."}]},{"t":"p","runs":[{"text":"When you need to compute a value on access, or validate on assignment, "},{"text":"@property","code":true},{"text":" makes a method look like an attribute:"}]},{"t":"code","lang":"python","label":"Python","text":"    @property\n    def turns(self):\n        return sum(\n            1\n            for m in self.messages\n            if m[\"role\"] != \"system\"\n        )"},{"t":"p","runs":[{"text":"c.turns","code":true},{"text":" (no brackets) calls the method. Use it for cheap derived values. A property that makes a network call is a trap for whoever reads "},{"text":"c.turns","code":true},{"text":" in a loop."}]},{"t":"h2","id":"when-not-to-write-a-class","runs":[{"text":"When not to write a class"}]},{"t":"p","runs":[{"text":"A class is not a badge of seriousness. If a dict does the job and no functions cluster around it, keep the dict. If you have a function and some fixed settings, a function with default arguments or a closure is simpler than a class with one method. Classes earn their place when data and behaviour belong together, or when you need several objects of the same shape that carry their own state: one "},{"text":"Conversation","code":true},{"text":" per user, one "},{"text":"Budget","code":true},{"text":" per job."}]},{"t":"p","runs":[{"text":"The "},{"text":"Budget","code":true},{"text":" class from the previous module is the pattern at its smallest: two numbers and the one method that changes them, kept together so that nobody updates one without the other."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Write "},{"text":"Conversation","code":true},{"text":" with "},{"text":"add","code":true},{"text":", "},{"text":"last","code":true},{"text":", "},{"text":"__repr__","code":true},{"text":", and a "},{"text":"token_estimate","code":true},{"text":" method that sums "},{"text":"len(content) // 4","code":true},{"text":" across messages. Then rewrite it with "},{"text":"messages = []","code":true},{"text":" in the class body, create two instances, and watch them share. Put it back."}]}],"check":{"question":[{"text":"A developer writes "},{"text":"class Conversation:","code":true},{"text":" with "},{"text":"messages = []","code":true},{"text":" declared directly in the class body, and an "},{"text":"add(self, role, text)","code":true},{"text":" method that appends to "},{"text":"self.messages","code":true},{"text":". They create two conversations, add a message to the first, and find the second conversation contains it too. Why?"}],"options":[{"text":[{"text":"append","code":true},{"text":" on a list inside a method always modifies the most recently created instance rather than "},{"text":"self","code":true},{"text":"."}],"correct":false,"tempting":[{"text":"Methods act on whichever object they were called on; there is no notion of most recent."}]},{"text":[{"text":"Two instances of the same class share memory until one of them is modified, at which point Python copies the object, and the copy happened only after the append had already been applied to both."}],"correct":false,"tempting":[{"text":"Python has no copy-on-write for instances; each object has its own attribute dictionary from the moment it is created."}]},{"text":[{"text":"The "},{"text":"add","code":true},{"text":" method is missing a "},{"text":"return","code":true},{"text":", so the appended list is discarded and the class-level list is used as a fallback."}],"correct":false,"tempting":[{"text":"append","code":true},{"text":" mutates in place and returns nothing whatever the method returns; the fallback described does not exist."}]},{"text":[{"text":"messages = []","code":true},{"text":" in the class body makes one list on the class, and "},{"text":"self.messages","code":true},{"text":" falls through to it because no instance got its own in "},{"text":"__init__","code":true},{"text":"."}],"correct":true,"tempting":null}],"order":[0,1,2,3],"why":null},"prev":{"slug":"counting-tokens-and-cost","title":"Knowing what each call cost: usage figures, token counting, and a budget that stops the program","minutes":9},"next":{"slug":"dataclasses","title":"Dataclasses: the class that is mostly data, written in four lines","minutes":8}}}