androidengineers.Book a session

Python 08 · Objects and interfaces

Classes, instances, and encapsulated behavior

articleSelf-paced

Learn the concept

A class groups state with operations on that state. An instance is one concrete object created from the class. self refers to the current instance in a method. Instance attributes belong to each object; class attributes are shared through the class unless overridden.

Use a class when an object has meaningful state or behavior, not merely to wrap every function. Keep invariants inside methods that update the state. If a counter must never become negative, enforce that rule where updates occur.

Avoid shared mutable class attributes for per-request data. Two users can accidentally share a list when it was intended to belong to each instance. Initialize independent containers inside the constructor. Prefer a small public interface that exposes what callers need without forcing them to manipulate internal representation.

Run and inspect

class Queue:
    def __init__(self):
        self.items = []
    def add(self, item):
        self.items.append(item)

a, b = Queue(), Queue()
a.add("job")
assert a.items == ["job"]
assert b.items == []

Your exercise

Build a task object with pending, running, and complete states. Reject a transition directly from pending to complete.

Check your understanding

Two instances do not share mutable state and invalid transitions produce explicit errors.

YOUR LEARNING JOURNEY

0 of 118 available lessons completed

Progress saved in this browser. No account needed.
Classes, instances, and encapsulated behavior | Agentic AI | Android Engineers