Classes
A class is a blueprint for objects: it names a type, holds methods, and describes the attributes each instance will carry. class Order: creates that type; calling Order(...) creates an instance.
Detailed Explanation
A class is how you teach Python a new kind of object. The class statement runs a body, collects the names defined there, and builds a type object. Functions in the body become methods. Assignments in the body become class attributes, shared by every instance unless an instance shadows them.
You create an instance by calling the class. Order("A-1", 2) looks up __new__ to allocate the object, then __init__ to initialise it. The instance stores its own data on self. Methods are functions that receive that instance as the first argument.
A class is itself an object. It has a name, a module, a dictionary of attributes, and a tuple of bases. Order.tax = 0.2 adds a class attribute after the fact. type(Order) is type unless you wrote a metaclass. Because classes are objects, you can pass them to functions, store them in registries, and create them dynamically with type("Name", bases, namespace).
Inheritance lists other classes in the header: class PriorityOrder(Order):. Python searches the method resolution order for attributes the subclass does not define. Multiple inheritance is allowed and uses C3 linearisation. That is a feature with a dedicated entry; most application classes have one base, or object implicitly.
Class bodies are executable. for loops, if flags, and imports run at definition time, once, when the module is imported. That is why a mutable class attribute (ids = []) is created once and shared. Instance state belongs in __init__.
Use a class when several pieces of data and the operations on them belong together, or when you need polymorphism. Use a function, a dataclass, or a NamedTuple when you only need a bag of fields. A module-level function plus a dict is often clearer than a one-method class.
Code Examples
class Order:
tax = 0.2 # class attribute, shared
def __init__(self, sku: str, qty: int):
self.sku = sku # instance attributes
self.qty = qty
def cents(self, unit_price: int) -> int:
return int(self.qty * unit_price * (1 + self.tax))
line = Order("A-1", 2)
print(line.sku, line.cents(500)) # A-1 1200
print(type(line), type(Order)) # <class '__main__.Order'> <class 'type'># The class body runs at definition time.
class Status:
labels = {0: "new", 1: "paid"}
names = list(labels.values())
print(Status.names) # ['new', 'paid']Common Gotchas
Mutable class attributes are shared
`class Cart: items = []` gives every cart the same list. Create `self.items = []` in `__init__`.
Calling the class is not calling `__init__` only
`__new__` runs first and can return an existing object. That is how some singletons work.
A method is a function until it is looked up on an instance
`Order.cents` is a function. `line.cents` is a bound method. Storing `line.cents` keeps `line` alive.