OOP Deeper
Chapter 14 built classes that store data and act on it through self. Real classes need more than that: a helper that belongs to the class but doesn't touch any one object's data, a second way to build an object besides __init__, a convention for signaling "don't touch this from outside," and a way to validate data the instant it's assigned instead of hoping every caller remembers to call a setter method. This chapter covers all four, still without touching inheritance.
How to read this chapter
- These are all still just tools inside one class — nothing here involves one class extending another. Inheritance is Chapter 16.
- Sub-topics build toward one idea: a class can start simple and grow safely. A plain attribute today can become a validated property tomorrow without breaking any code that already uses the class.
- Python has no true "private" keyword. Sub-topic 3 covers the honest reality of Python's privacy conventions before Sub-topics 4 and 5 show why that matters for properties.
Account class six months after launch. It shipped with a plain balance attribute, and by now dozens of other files read and write acct.balance directly. Then a bug report comes in: nothing stops acct.balance = -500 from silently creating an account in the red. Rewriting every one of those dozens of call sites to use a new set_balance() method would take days and risk missing one. This chapter's tools — @property especially — are exactly how experienced Python developers solve this without breaking anything already using the class.
1. @staticmethod
- A static method lives inside a class for logical organization, but doesn't need
selfor the class itself to do its job. - It's marked with the
@staticmethoddecorator directly above the method definition. - Use it for a helper that's clearly related to the class, even though it doesn't read or change any specific object's data.
self as its first parameter, because every one of them touched some object's own data. Not every useful method actually needs that.
Take a validation check like "is this a usable deposit amount?" It doesn't need to know which account is depositing — it only needs the amount itself:
self nor
the class itself as a parameter. It behaves like a regular
function that just happens to live inside the class's namespace.
class Account:
@staticmethod
def is_valid_amount(amount):
return isinstance(amount, (int, float)) and amount > 0
print(Account.is_valid_amount(50))
print(Account.is_valid_amount(-10))
print(Account.is_valid_amount("fifty"))
True
False
False
Notice Account.is_valid_amount(50) is called directly
on the class, not on an object — there's no account involved yet,
because none is needed. This is the tell that a method should be
static: if the body never touches self.anything, it
doesn't need self at all.
A static method still gets used from inside instance methods, keeping the validation logic in exactly one place instead of copy-pasted everywhere a deposit might happen:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
@staticmethod
def is_valid_amount(amount):
return isinstance(amount, (int, float)) and amount > 0
def deposit(self, amount):
if not Account.is_valid_amount(amount):
print("Invalid deposit amount.")
return
self.balance += amount
acct = Account("Alice", 100)
acct.deposit(50)
print(acct.balance)
acct.deposit(-20)
print(acct.balance)
150
Invalid deposit amount.
150
deposit still uses self, because it
changes self.balance. is_valid_amount
never needs self, because checking whether a number
is valid has nothing to do with any specific account.
Go Deeper: static methods also run fine on an instance
acct.is_valid_amount(50) works exactly the same as
Account.is_valid_amount(50) — Python doesn't pass
acct in as an extra argument, since the method was
never defined to accept it. Most codebases still prefer calling
static methods on the class directly, since that reads as "this
doesn't depend on any specific object."
- A static method, marked with
@staticmethod, takes noselfand no class parameter. - Use it for a helper that's logically related to the class but doesn't need any specific object's data.
- It's called on the class directly, like
Account.is_valid_amount(50).
2. @classmethod & alternative constructors
- A class method takes
cls(the class itself) as its first parameter instead ofself. - It's marked with
@classmethod, and can read class attributes or even build new instances viacls(...). - The single most common real use is an alternative constructor — a second way to build an object besides
__init__.
__init__ only supports one calling pattern. Real data doesn't always arrive in that exact shape — sometimes it arrives as one comma-separated string from a file, and reshaping it shouldn't be the caller's problem.
A class method looks almost identical to a static method, except for that first parameter:
cls?
cls refers to the class itself, the same way
self refers to one specific object. Python fills it
in automatically for any method marked @classmethod,
the same automatic-first-argument rule self already
follows.
class Account:
bank_name = "Acme Bank"
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
@classmethod
def bank_info(cls):
return f"{cls.bank_name} (accounts built from {cls.__name__})"
print(Account.bank_info())
Acme Bank (accounts built from Account)
@classmethod, takes
cls as its first parameter instead of self.
It operates on the class itself — its class attributes, or building
new instances of it — rather than any one object's data.
The genuinely useful pattern shows up when a class needs a second
way to build an object. Picture account data arriving from a file
as one string, "Bob,250.0", instead of two separate
arguments — an alternative constructor reshapes it
before handing off to __init__:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
@classmethod
def from_string(cls, account_data):
owner, balance = account_data.split(",")
return cls(owner, float(balance))
def __str__(self):
return f"Account(owner={self.owner!r}, balance={self.balance})"
acct1 = Account("Alice", 100)
acct2 = Account.from_string("Bob,250.0")
print(acct1)
print(acct2)
Account(owner='Alice', balance=100)
Account(owner='Bob', balance=250.0)
cls(owner, float(balance)) is doing exactly what
Account(owner, float(balance)) would do — calling
cls instead of hardcoding Account means
this same method would still work correctly even if this class
were renamed later. from_string reads as "build an
Account a different way," while __init__
stays the one place that actually sets up the object's attributes.
Go Deeper: why not just use @staticmethod here instead?
from_string could technically be written as a
static method that calls Account(...) directly by
name — but then renaming the class would silently break every
alternative constructor still hardcoding the old name. Using
cls(...) is the one real reason to reach for
@classmethod instead of @staticmethod
when building new instances.
- A class method, marked
@classmethod, takescls(the class) as its first parameter. - Its most common real use is an alternative constructor — a second way to build an object, reshaping different input before calling
cls(...). - Using
cls(...)instead of the hardcoded class name keeps the method correct even if the class is later renamed.
3. Encapsulation & "private" attributes
- A single leading underscore, like
_balance, is a convention signaling "treat this as internal" — Python does not actually enforce it. - A double leading underscore, like
__balance, triggers name mangling, a much stronger (but still not truly unbreakable) hint. - Python's philosophy here is often summarized as "we're all consenting adults" — there's no true enforced privacy like some other languages have.
Some languages have a private keyword that the
compiler genuinely enforces — code outside the class simply
cannot access that attribute at all. Python has no such keyword.
Instead, a single underscore prefix is a naming convention every
Python developer recognizes:
_balance signals "this is an internal
implementation detail — don't touch it directly from outside the
class," but Python enforces absolutely nothing. The underscore is
purely a communication tool between developers.
class Account:
def __init__(self, owner, balance):
self.owner = owner
self._balance = balance
def deposit(self, amount):
self._balance += amount
acct = Account("Alice", 100)
acct.deposit(50)
print(acct._balance)
acct._balance = -999
print(acct._balance)
150
-999
acct._balance = -999 ran without any error at all —
the underscore is a signal to a human reading the code, not a lock
Python checks. This is exactly the gap Sub-topic 5's property
setter closes.
A double underscore prefix, like __balance, goes one
step further with a real (if narrow) mechanism called
name mangling:
__balance (inside a class
named Account) to _Account__balance. This
makes accidental access or accidental overriding by unrelated code
much less likely, but it's still not a true lock — the mangled
name is discoverable and still directly accessible.
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
def get_balance(self):
return self.__balance
acct = Account("Alice", 100)
print(acct.get_balance())
print(acct._Account__balance)
try:
print(acct.__balance)
except AttributeError as e:
print("AttributeError:", e)
100
100
AttributeError: 'Account' object has no attribute '__balance'
acct.__balance fails, since that exact name was never
actually created — Python quietly renamed it to
_Account__balance during class creation. But
acct._Account__balance still works, proving this is
an obstacle, not a wall.
The practical takeaway most Python codebases actually follow: use
a single underscore, like _balance, to mark
"internal, please don't touch directly" — and reach for
@property (Sub-topics 4 and 5) when there's a real
need to actually control access, rather than relying on naming
alone.
Go Deeper: double underscore is usually overkill
Name mangling exists mainly to prevent accidental name clashes in larger class hierarchies (relevant once inheritance enters the picture in Chapter 16), not as a privacy tool for everyday classes. Most real Python code reaches for a single underscore, not two, for routine "internal" attributes.
- A single underscore, like
_balance, is an unenforced convention meaning "internal, don't touch directly." - A double underscore, like
__balance, triggers name mangling to_ClassName__name— a stronger hint, still not a true lock. - Python's "we're all consenting adults" philosophy means there's no truly enforced private access, unlike some other languages.
4. @property
- A property is a getter method that's accessed like a plain attribute, not called like a method.
- It's created by putting
@propertydirectly above a method that returns a value. acct.balancereads more naturally thanacct.get_balance(), while still running real code behind the scenes.
_balance precisely so a property could control access to it — this is where that setup pays off.
A method decorated with @property is called without
parentheses at all, exactly like reading a regular attribute:
@property that
gets accessed using plain attribute syntax, like
acct.balance, instead of method-call syntax like
acct.balance(). It behaves like an attribute from the
outside, while still running actual code every time it's read.
class Account:
def __init__(self, owner, balance):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
acct = Account("Alice", 100)
print(acct.balance)
100
acct.balance — no parentheses — runs the
balance method and returns its result. Writing
acct.balance() instead would actually raise a
TypeError, since the property is no longer callable
once it's wrapped this way; it behaves as an attribute now, fully.
The real reason this beats a plain get_balance()
method is readability at the call site — compare them side by
side:
class AccountOld:
def __init__(self, balance):
self._balance = balance
def get_balance(self):
return self._balance
class AccountNew:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
old = AccountOld(100)
new = AccountNew(100)
print(old.get_balance())
print(new.balance)
100
100
new.balance reads like "this account's balance,"
matching how acct.owner already reads for a plain
attribute — a caller shouldn't need to remember which attributes
are "real" and which ones require an extra () just to
read.
Go Deeper: a property with no setter is read-only
Account above has no way to write
acct.balance = 300 yet — attempting it raises an
AttributeError, since only a getter was defined.
Sub-topic 5 adds the matching setter to allow controlled
assignment.
- A property, marked
@property, is a getter method accessed like a plain attribute — no parentheses. acct.balancereads more naturally thanacct.get_balance(), while still running real code.- A property with only a getter is read-only — assigning to it raises an error until a setter is added.
5. Property setters
- A setter, marked
@balance.setter, runs automatically whenever code writesacct.balance = value. - It's the natural place to validate data at the point of assignment, instead of trusting every caller to remember a separate check.
- The setter method must share the exact same name as the property it's attached to.
acct._balance = -999 succeeding silently. A setter is how a class actually stops that, without callers needing to remember to call a separate validation method themselves.
A setter is written just below the matching @property
getter, decorated with @name.setter using that same
property's name:
@propertyname.setter
that Python calls automatically whenever
obj.propertyname = value is written. It receives
value as a parameter and decides what happens next —
including rejecting the assignment entirely.
class Account:
def __init__(self, owner, balance):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative.")
self._balance = value
acct = Account("Alice", 100)
print(acct.balance)
acct.balance = 250
print(acct.balance)
try:
acct.balance = -50
except ValueError as e:
print("ValueError:", e)
print(acct.balance)
100
250
ValueError: Balance cannot be negative.
250
acct.balance = 250 looks exactly like assigning to a
plain attribute, but it's really calling the setter method with
value = 250. acct.balance = -50 triggers
the exact same setter, and this time the validation check inside
it raises ValueError before self._balance
is ever touched — the balance stays at 250, not
-50.
This is the direct fix for Sub-topic 3's gap: as long as every
part of the class reads and writes self.balance (the
property) instead of self._balance (the raw
attribute) directly, there is now exactly one gatekeeper for every
assignment, no matter how many places in a program try to change
it.
Go Deeper: __init__ can go through the setter too
Writing self.balance = balance inside
__init__ (instead of self._balance =
balance) routes even the very first assignment through
the same validation — so Account("Alice", -50)
would raise the same ValueError immediately, rather
than only catching bad values assigned later.
- A setter, marked
@name.setter, runs automatically onobj.name = valueassignment. - It's the natural place to validate data right at the point of assignment, instead of trusting a separate method to be called correctly.
- Raising an error inside the setter blocks the bad assignment entirely — the underlying attribute is never updated.
6. Real-world deeper OOP in production
- Upgrading a plain attribute to a validated property never breaks code that already reads or writes it with plain attribute syntax.
- Static methods keep related helper logic organized inside the class it serves; class methods provide alternative constructors for real-world data shapes.
- All four tools from this chapter combine naturally in one realistic class, without needing inheritance.
This chapter's opening hook described a real bug: a banking app
shipped with a plain balance attribute, and nothing
stopped it from going negative. Here's the fix, combining every
sub-topic from this chapter into one class:
class Account:
bank_name = "Acme Bank"
def __init__(self, owner, balance):
self.owner = owner
self._balance = balance
@staticmethod
def is_valid_amount(amount):
return isinstance(amount, (int, float)) and amount > 0
@classmethod
def from_string(cls, account_data):
owner, balance = account_data.split(",")
return cls(owner, float(balance))
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative.")
self._balance = value
def deposit(self, amount):
if not Account.is_valid_amount(amount):
print("Invalid deposit amount.")
return
self.balance += amount
def __str__(self):
return f"Account(owner={self.owner!r}, balance={self.balance})"
acct1 = Account("Alice", 100)
acct2 = Account.from_string("Bob,300")
acct1.deposit(50)
print(acct1)
print(acct2)
try:
acct1.balance = -10
except ValueError as e:
print("ValueError:", e)
print(acct1.balance)
print(Account.bank_name)
Account(owner='Alice', balance=150)
Account(owner='Bob', balance=300.0)
ValueError: Balance cannot be negative.
150
Acme Bank
Every sub-topic is doing real work here: is_valid_amount
is a static method, since checking a number needs no specific
account; from_string is a class method serving as an
alternative constructor for data arriving as one string;
_balance follows the single-underscore convention;
and the balance property's getter and setter together
make sure self.balance += amount inside
deposit still passes through the same validation as
any other assignment.
The detail worth sitting with: acct1.deposit(50) and
print(acct1.balance) are written exactly the way they
would have been written in Chapter 14, before any property
existed. A class can start with a plain self.balance
attribute and upgrade to this validated property later — every
line of code anywhere else that reads or writes
acct.balance keeps working completely unchanged,
because the syntax on the outside never had to change at all.
- Real ORMs and data-validation libraries (the kind that sit behind web forms and databases) lean heavily on properties to validate a field the instant it's assigned, exactly like this chapter's
balancesetter. - Alternative constructors are everywhere in real libraries — building an object
from_string,from_dict, orfrom_jsonalongside a normal__init__is one of the most common class-method patterns in production Python. - Static methods keep a class's file from becoming a dumping ground for unrelated helper functions elsewhere in a codebase — a validation helper tied to one class's data belongs inside that class, not floating in some unrelated utilities file.
Go Deeper: what's still missing without inheritance?
Account above is still one single, self-contained
class — there's no way yet to say "a
SavingsAccount is an Account, plus
interest," the same gap Chapter 14 left open. That relationship
is exactly what Chapter 16 builds directly on top of everything
in this chapter.
- Static methods, class methods, and properties all combine naturally inside one class, with no inheritance required.
- Upgrading a plain attribute to a validated property never breaks existing code that reads or writes it using ordinary attribute syntax.
- Alternative constructors, validation helpers, and validated assignment are genuine, common patterns in real production Python.
- Web frameworks and ORMs (the tools behind real websites and databases) validate incoming data through properties exactly like this chapter's
balancesetter, catching bad values the instant they're assigned rather than downstream. - Alternative constructors like
from_string,from_dict, andfrom_jsonare a standard pattern across real Python libraries for accepting data in whatever shape it actually arrives in. - Upgrading a plain attribute to a property without breaking any existing caller is a genuinely common refactor in real, mature codebases — it's a big part of why Python developers default to plain attributes early and add properties only once real validation is actually needed.
Points to Remember
- A static method (
@staticmethod) takes neitherselfnorcls— use it for a helper that's related to the class but doesn't need any specific object's data. - A class method (
@classmethod) takesclsas its first parameter; its most common real use is an alternative constructor that reshapes different input before callingcls(...). - A single underscore (
_balance) is an unenforced convention for "internal, don't touch"; a double underscore (__balance) triggers name mangling to_ClassName__name— Python has no truly enforced privacy either way. - A property (
@property) is a getter method accessed like a plain attribute, with no parentheses — it reads more naturally than a separateget_x()method. - A property setter (
@name.setter) runs automatically on assignment, making it the natural place to validate data right when it's set, instead of trusting every caller to remember a separate check. - Upgrading a plain attribute into a validated property never breaks existing code that already reads or writes it with ordinary attribute syntax — this is why starting simple and upgrading later is standard practice, not a shortcut.