A class bundles data and behavior into your own kind of thing; an object is one concrete instance built from it.
Core terms
- Class: the blueprint (written once). Object / instance: a concrete thing built from it (many).
- Attribute: data stored on an object, read as
obj.x. Each object has its own. - Method: a function defined inside a class; takes
selffirst. p is qisFalsefor two separate objects even if built the same way.
__init__ and self
__init__runs at construction to set starting data.selfis the object being worked on; Python passes it automatically. You never pass it yourself.self.x = xstores valuexonto this object. Set per-object data here.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to_origin(self):
return (self.x**2 + self.y**2) ** 0.5
Dunder methods
- Dunder (double-underscore) methods run on built-in syntax:
__init__— construction.__repr__— printing; must return a string, ideally one that recreates the object.__len__— makeslen(obj)work.__eq__— defines==; without it,==compares identity (memory), not contents.
Encapsulation
- Encapsulation: keep internal data private, interact only through methods.
- Leading underscore (
self._items) means “internal, do not touch from outside.” Convention only, not enforced. - Public methods can stay stable while internals change.
Class vs dict
- dict: plain data, no behavior; keys not fixed or decided at runtime; a quick bag of values.
- class: data has behavior (methods); fixed reusable shape; want
__repr__,__eq__, or encapsulation; many instances. - Functions that all take the same dict first argument want to be a class.
Pitfalls
- Forgetting
self— useself.x, not barex, or you get a local variable. - Method without
()—p.methodis the function object;p.method()calls it. - Mutable value in the class body (e.g.
items = []outside a method) is shared by every instance; initialize in__init__. ==compares identity until you define__eq__.pop/peekon an empty container raises; checkis_empty()first.