UcenlyOpen in the app

Programming Essentials · BE5B33PRG · Topic 8 of 9

Classes, instances and methods

Bundle state with operations that maintain it.

Open the interactive lesson

Key ideas

Instance state

class Counter: defines a type; __init__(self, start) stores self.value = start for each instance.

Methods

def inc(self): self.value += 1 changes that instance. Calling c.inc() supplies c as self.

Representation

__str__ defines user-facing text. A class variable is shared through the class unless shadowed on an instance.

Properties

@property exposes a computed value with attribute syntax; choose it for a stable, meaningful interface.

In one line: Identify which state belongs to each instance and which belongs to the class.

Sources

Written by Ucenly. Based on the BE5B33PRG course materials: