🐍 Python for Everyone

← Back to all chapters

Chapter 15 of 27 Intermediate 60 min read

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

Picture a banking app's 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.
Sub-topic 1 of 6

1. @staticmethod

At a glance
  • A static method lives inside a class for logical organization, but doesn't need self or the class itself to do its job.
  • It's marked with the @staticmethod decorator 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.
Why this matters: every method in Chapter 14 took 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:

What is... a static method? A static method is a method that belongs to a class for organizational purposes, but takes neither self nor the class itself as a parameter. It behaves like a regular function that just happens to live inside the class's namespace.
static_method_demo.py
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"))
actual output of static_method_demo.py
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:

static_method_used_internally.py
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)
actual output of static_method_used_internally.py
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.

try_it.py
Click "Run Code" — try adding a check for amount == 0, since 0 isn't > 0 already.
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."

Quick recap
  • A static method, marked with @staticmethod, takes no self and 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).
Sub-topic 2 of 6

2. @classmethod & alternative constructors

At a glance
  • A class method takes cls (the class itself) as its first parameter instead of self.
  • It's marked with @classmethod, and can read class attributes or even build new instances via cls(...).
  • The single most common real use is an alternative constructor — a second way to build an object besides __init__.
Why this matters: __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:

What is... 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.
classmethod_basic.py
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())
actual output of classmethod_basic.py
Acme Bank (accounts built from Account)
What is... a class method? A class method, marked with @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__:

alternative_constructor.py
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)
actual output of alternative_constructor.py
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.

try_it.py
Click "Run Code" — try building a second account from a different string.
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.

Quick recap
  • A class method, marked @classmethod, takes cls (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.
Sub-topic 3 of 6

3. Encapsulation & "private" attributes

At a glance
  • 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.
Why this matters: the next two sub-topics wrap a "private" attribute in a property — this sub-topic explains what "private" honestly means in Python first, so that doesn't read as a contradiction.

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:

What is... the single-underscore convention? A name like _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.
single_underscore_demo.py
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)
actual output of single_underscore_demo.py — nothing stopped the direct assignment
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:

What is... name mangling? Python internally rewrites __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.
double_underscore_demo.py
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)
actual output of double_underscore_demo.py
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.

What is... "we're all consenting adults"? A well-known summary of Python's design philosophy on privacy: the language trusts developers not to reach into another class's internals just because a language feature happens to make it technically possible, rather than trying to physically prevent it.

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.

Quick recap
  • 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.
Sub-topic 4 of 6

4. @property

At a glance
  • A property is a getter method that's accessed like a plain attribute, not called like a method.
  • It's created by putting @property directly above a method that returns a value.
  • acct.balance reads more naturally than acct.get_balance(), while still running real code behind the scenes.
Why this matters: Sub-topic 3 stored the real value in _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:

What is... a property? A property is a method marked with @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.
property_demo.py
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)
actual output of property_demo.py
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:

getter_vs_property.py
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)
actual output of getter_vs_property.py — same value, more natural read on the second line
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.

try_it.py
Click "Run Code" — try acct.balance() with parentheses to see the TypeError.
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.

Quick recap
  • A property, marked @property, is a getter method accessed like a plain attribute — no parentheses.
  • acct.balance reads more naturally than acct.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.
Sub-topic 5 of 6

5. Property setters

At a glance
  • A setter, marked @balance.setter, runs automatically whenever code writes acct.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.
Why this matters: Sub-topic 3 showed 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:

What is... a property setter? A setter is a method decorated with @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.
property_setter_demo.py
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)
actual output of property_setter_demo.py
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.

try_it.py
Click "Run Code" — try acct.balance = -100 to see the ValueError.
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.

Quick recap
  • A setter, marked @name.setter, runs automatically on obj.name = value assignment.
  • 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.
Sub-topic 6 of 6

6. Real-world deeper OOP in production

At a glance
  • 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.
Pattern to remember: it's completely normal — and considered good practice — to start a class with a plain attribute and upgrade to a property only once real validation is actually needed. Nothing about that upgrade requires touching any other file.

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:

account_full.py
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)
actual output of account_full.py
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.

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.

Quick recap
  • 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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →