Object-Oriented Programming (Part 1): Classes, Objects, __init__ and self
In small scripts, keeping data in dictionaries and passing them into standalone functions works well. As systems grow more complex, however, loose dictionaries become fragile: nothing stops a developer from misspelling a key name or passing an invalid dictionary into the wrong function. Object-Oriented Programming (OOP) solves this by bundling data (attributes) and the functions that operate on that data (methods) together inside a single blueprint called a class.
Classes vs Objects (Instances)
| Concept | Plain-English Analogy | In Python Code |
|---|---|---|
| Class | The architectural blueprint or template for an incident ticket | class IncidentTicket: (written in PascalCase) |
| Object (Instance) | A specific, real ticket created from that blueprint in memory | t1 = IncidentTicket("INC-101", "Database down") |
| Attribute | A piece of data stored on the object | t1.status, t1.ticket_id |
| Method | An action or behaviour attached to the object | t1.resolve("Restarted DB cluster") |
Defining a Class: __init__ and self Explained
When you create a new object from a class, Python automatically calls the special initializer method named __init__. The first parameter of every instance method is named self, which refers to the specific object instance currently being created or acted upon:
class ServerNode:
# Class attribute (shared across all instances)
default_ssh_port = 22
def __init__(self, hostname: str, ip_address: str):
# Instance attributes (unique to each server object)
self.hostname = hostname
self.ip_address = ip_address
self.is_online = False
def bring_online(self) -> None:
self.is_online = True
print(f"[OK] {self.hostname} ({self.ip_address}) is now ONLINE.")
def status_summary(self) -> str:
state = "ONLINE" if self.is_online else "OFFLINE"
return f"{self.hostname} [{self.ip_address}:{self.default_ssh_port}] -> {state}"
# Creating two independent instances from the ServerNode blueprint
web_srv = ServerNode("srv-web-01", "10.0.1.10")
db_srv = ServerNode("srv-db-01", "10.0.1.50")
web_srv.bring_online()
print(web_srv.status_summary())
print(db_srv.status_summary())
Encapsulation and Properties (@property)
To prevent callers from setting invalid state (such as a negative port number or an empty hostname), prefix internal attributes with a single underscore (self._cpu_limit) and expose validated access using the @property decorator:
class ServiceQuota:
def __init__(self, max_connections: int):
self.max_connections = max_connections # Calls setter below
@property
def max_connections(self) -> int:
return self._max_connections
@max_connections.setter
def max_connections(self, value: int) -> None:
if value < 1 or value > 10000:
raise ValueError("max_connections must be between 1 and 10,000.")
self._max_connections = value
quota = ServiceQuota(500)
quota.max_connections = 1200 # Validated automatically!
Common Mistakes
- Forgetting
selfas the first parameter of a method: Writingdef start():inside a class causes aTypeError: start() takes 0 positional arguments but 1 was givenbecause Python always passes the instance itself as the first argument. - Defining mutable lists as class attributes instead of inside
__init__: Puttingtags = []directly underclass Server:shares the exact same list across every server instance! Always initialise per-object lists inside__init__usingself.tags = [].
- A class (
PascalCase) is a blueprint that bundles state (attributes) and behaviour (methods); an object is a concrete instance of that class. - Use
__init__(self, ...)to set up unique instance attributes on creation. - Use
@propertyto add validation logic to attributes without breaking how callers read or assign them.