Python Classes Objects
Tutorial 20 of 65 · pythondeck.com Python course
Classes group state and behaviour. The __init__ method initialises a new instance. Methods take self as the first parameter. Use @classmethod and @staticmethod for alternative method types and @dataclass for boilerplate-free records.
Classes define new types; objects are instances with state (attributes) and behavior (methods). Object-oriented Python models real-world entities and encapsulates invariants behind methods.
Even without heavy OOP, classes organize code for GUIs, APIs, and data holders—dataclasses reduce boilerplate for simple record types. Built-ins like list are classes too, so methods you already use are the same model you extend. Instances store attributes in a per-object dict unless you opt into slots for memory tuning.
class Name: with methods; first param of instance methods is self.
__init__ initializes instance state; not a constructor in the C++ sense.
Instance vs class attributes: shared class attrs can surprise if mutated on instances.
@classmethod and @staticmethod for alternate constructors and utilities.
Special methods: __repr__, __str__, __eq__ customize protocols.
Properties @property expose computed attributes with validation.
Everything is an object, including functions and modules. Classes are objects too—metaclass is usually type.
Composition over inheritance: hold other objects as attributes instead of deep trees.
Dataclasses auto-generate boilerplate; __slots__ trades dynamic attributes for memory on huge instance counts.
Forgetting self in method definitions or calls.
Mutable class-level lists shared by all instances.
Overusing inheritance for code reuse where a simple function suffices.
Implementing __eq__ without considering hashability for dict keys.
Keep __init__ cheap; defer heavy work to explicit methods or factories.
Implement __repr__ for debugging; __str__ for user-facing messages.
Use dataclass or NamedTuple for records; classes with behavior when methods coordinate state.
Follow one responsibility per class in larger codebases.
Sketch class relationships on paper before adding another subclass—MRO surprises are cheaper early.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates basic class. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Basic class
# Run in the REPL or save as a .py file and execute with python.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def distance(self):
return (self.x**2 + self.y**2) ** 0.5
p = Point(3, 4)
print(p.distance())
This sample walks through classmethod / staticmethod in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: classmethod / staticmethod
# Run in the REPL or save as a .py file and execute with python.
class Temp:
def __init__(self, c):
self.c = c
@classmethod
def from_f(cls, f):
return cls((f - 32) * 5/9)
@staticmethod
def freezing():
return 0
t = Temp.from_f(212)
print(t.c, Temp.freezing())
Here is a hands-on illustration of dataclass. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: dataclass
# Run in the REPL or save as a .py file and execute with python.
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int = 0
print(User("Ada", 36))
The program below demonstrates instance methods. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# class bundles data (attributes) with behavior (methods)
class Counter: # simple mutable counter type
def __init__(self, start=0): # constructor sets state
self.value = start # instance attribute
def inc(self, step=1): # method takes self + args
self.value += step # mutate internal state
def __repr__(self): # developer-friendly display
return f"Counter({self.value})" # repr string
c = Counter(10) # construct instance
c.inc(5) # call bound method
print(c) # Counter(15)
This sample walks through class attribute in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Attributes on the class are shared; instance attrs shadow them
class User: # user model
role = "member" # class-level default
def __init__(self, name): # per-instance name
self.name = name # instance attribute
u1 = User("Ada") # regular member
u2 = User("Admin") # will promote
u2.role = "admin" # instance overrides class attr
print(u1.role, u2.role) # member admin
User.role = "guest" # changing class attr affects users without override
print(u1.role, u2.role) # guest admin