A Python class defines a type that groups data and the operations that work on it. Calling a class such as ReadingList("Weekend") normally creates an instance. Python then calls __init__ to initialize it. Inside a method, self refers to the instance receiving the call.
class ReadingList:
def __init__(self, title):
self.title = title
self.pages = []
def add_page(self, url):
self.pages.append(url)
weekend = ReadingList("Weekend")
work = ReadingList("Work")
weekend.add_page("/articles/")
assert weekend.pages == ["/articles/"]
assert work.pages == []
The two calls create separate lists. When you call weekend.add_page("/articles/"), Python passes weekend as self. That is why the method edits the weekend list and leaves the work list empty.
Instance attributes versus class attributes
An assignment in __init__ such as self.pages = [] creates an instance attribute. Writing pages = [] directly in the class body creates a class attribute. Access through an instance may then find the shared class list when an instance attribute is absent.
Use a class attribute for a value the instances intentionally share. Give each instance its own saved pages by creating a new list in __init__. To check that ownership, create two instances, add one page to the first, and check whether the other stays empty.
Give methods a reason to exist
A method should provide an operation in terms of the object. A reading list might offer add_page so it can enforce a rule about supported entries. Callers should have one obvious route to make an ordinary edit. If every caller has to patch three attributes in the right order, the class is exposing a fragile operation.
A leading underscore can mark an attribute as an implementation detail by convention. It does not grant access control. If callers must be physically prevented from editing data, design the storage and access boundary with that requirement in mind. For most in-process code, a clear public method and a small set of documented attributes give callers enough direction.
Keep object initialization predictable
__init__ initializes an instance that has already been created. Leave out a return value. Python raises TypeError if __init__ returns anything other than None. If a reading list needs a nonblank title, reject a blank one there so the caller knows immediately why creation failed.
Constructors that quietly open files or perform unrelated actions are harder to test and can leave side effects when initialization fails. Pass an already loaded value to the constructor or use a named factory that tells the reader it will load something. The person calling ReadingList("Work") then knows that they are creating a record in memory.
Know when a class adds unnecessary work
If an operation maps one value to another without retained state, a function is enough. A dictionary is convenient when field names come from the data itself, such as a JSON record. A dataclass can reduce repetition for stable named fields when you want attribute access and an explicit record type.
A class becomes easier to justify when multiple operations share an invariant. For example, a bounded history keeps recent entries up to a configured limit. Putting the limit and entries together lets every append enforce the same rule. Test two objects with different limits and make sure using one does not affect the other.
Inheritance is optional. Many small designs read clearly when one object holds another object and delegates a specific task. Reach for inheritance when the subtype really fulfills the caller's expectations of the original type, including what its methods return and which errors they raise.
Protect the operation that changes the state
Imagine a queue that can hold no more than its capacity. An ordinary list allows an append at any time. A queue class can put the capacity rule in one method and reject an extra item at the point where a caller tries to add it.
class BoundedQueue:
def __init__(self, capacity):
if type(capacity) is not int or capacity < 1:
raise ValueError("Capacity must be a positive integer")
self._capacity = capacity
self._items = []
def add(self, item):
if len(self._items) >= self._capacity:
raise OverflowError("Queue is full")
self._items.append(item)
def snapshot(self):
return tuple(self._items)
queue = BoundedQueue(1)
queue.add("draft")
assert queue.snapshot() == ("draft",)
try:
queue.add("review")
except OverflowError:
assert queue.snapshot() == ("draft",)
else:
raise AssertionError("An overfull queue should reject an item")
The snapshot returns a tuple of current entries, so the caller cannot append a new entry through it. A mutable entry inside that tuple would still be shared. If entries themselves should be immutable, use a suitable representation or copy at the boundary. Here, _capacity belongs to the implementation, and callers have no public method that changes it.
This example is intentionally in memory. If several threads or processes add items at the same time, the length check and append need coordinated access. If the queue has to survive a process restart, it needs another storage choice. Putting work into a class helps organize the policy, but persistence and concurrency are separate design requirements.
Make the useful behavior easy to test
Test instance methods from the point of view of a caller. The queue example checks rejection through the public method and then asks for a snapshot. A test that asserts how the list is implemented would make it harder to switch from a list to a deque later. A test that verifies the order, capacity, and result after rejection can survive a change to the storage object.
Classes make sense when the state stays meaningful across calls. For a calculation that can take all its inputs up front and produce one result, begin with a function. A class can still emerge later if you find a real invariant or responsibility that belongs with a long-lived object.
One clue is that callers describe operations with verbs that belong to the same value. Add an item, inspect the current history, and clear the history all describe work on one history. Parse a date and format a list describe separate calculations, even if one script performs both. A class name should help the caller understand which data those methods share and how long that state is expected to live.