Lesson 23 of 30
In progress
Methods, properties and validation
Add behaviour to your objects, validate changes at the door, and expose computed values with properties instead of stale attributes.
An object that anyone can reach into and change is barely better than a dictionary. The methods you write decide which changes are allowed, and a property can make a calculated value look like a plain attribute.
What you will learn
- Write methods that change state through one controlled path.
- Use
@propertyfor computed values and validated assignment. - Recognise when a class method or static method is the right tool.
One door for every change
Instead of assigning account.balance directly, provide methods that enforce the rules. Every caller goes through the same checks, and the checks live in one place.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount <= 0:
raise ValueError("Withdrawal must be positive")
if amount > self.balance:
raise ValueError("Insufficient funds")
self.balance -= amount
return self.balance
ana = Account("Ana", 500)
print(ana.deposit(250))
print(ana.withdraw(100))
try:
ana.withdraw(5000)
except ValueError as error:
print("Refused:", error)
Press Run to see the output.
The balance is still a public attribute, so a determined caller can bypass the methods. Python trusts adults. The methods exist so the normal path is safe, not to make misuse impossible.
Properties make computed values honest
A derived value stored as an attribute can go stale. A property calculates it on demand.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
@property
def area(self):
return self.width * self.height
@property
def is_square(self):
return self.width == self.height
box = Rectangle(4, 5)
print(box.area)
print(box.is_square)
box.width = 5
print(box.area)
Press Run to see the output.
area is used like an attribute, without brackets, but it is computed each time. Changing width updates area automatically because nothing was cached. That is the correct default; cache only when measurement proves the calculation is expensive.
A property can also validate assignment with a setter:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("Price cannot be negative")
self._price = value
item = Product("Pen", 12)
print(item.price)
try:
item.price = -5
except ValueError as error:
print("Rejected:", error)
Press Run to see the output.
The leading underscore on _price is a convention meaning "internal". The property is the public door, and every assignment through it is checked. This is the Pythonic alternative to Java-style getters and setters for every field.
Class methods and static methods
An instance method receives the object. A class method receives the class, which is useful for alternative constructors. A static method receives neither, and is just a function namespaced inside the class.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
@classmethod
def from_fahrenheit(cls, fahrenheit):
return cls((fahrenheit – 32) * 5 / 9)
@staticmethod
def is_freezing(celsius):
return celsius <= 0
warm = Temperature.from_fahrenheit(86)
print(round(warm.celsius, 1))
print(Temperature.is_freezing(-2))
Press Run to see the output.
from_fahrenheit returns a new Temperature without the caller doing the conversion. is_freezing does not need the object or the class, so it is static. Use these sparingly; a plain function is often clearer than a static method.
Objects that behave like built-ins
Special methods with double underscores, read aloud as "dunder", let your objects work with the language itself. __len__ makes len(obj) work, __eq__ decides what equality means, and __iter__ lets a for loop walk the object.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def __len__(self):
return len(self.members)
def __eq__(self, other):
if not isinstance(other, Team):
return NotImplemented
return set(self.members) == set(other.members)
print(len(Team(["ana", "ravi"])))
print(Team(["ana", "ravi"]) == Team(["ravi", "ana"]))
Press Run to see the output.
Use these when the meaning is obvious. A playlist with __len__ is obvious; an account with __add__ that merges two balances is not. If a reader has to open the class to understand what a + b did, a named method would have been clearer.
A well-chosen dunder method removes boilerplate at every call site; a poorly chosen one hides a decision that should stay visible. The test is whether the operator’s meaning would surprise someone who has not read your class.
Two cautions. __eq__ should return NotImplemented for unrelated types rather than raising, so Python can try the other side. And defining __eq__ removes the default hash, so objects you put in a set need an explicit __hash__.
A property without a setter raises AttributeError: property 'area' of 'Rectangle' object has no setter when you assign to it. That is usually correct: box.area = 20 would contradict the dimensions. If assignment should be allowed, write the setter and decide what it changes.
Write a BankAccount with a private _balance and a read-only balance property. Add deposit and withdraw methods that validate, and a statement_line() method returning a formatted summary. Show that assigning account.balance = 1000 fails.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0 or amount > self._balance:
raise ValueError("Invalid withdrawal")
self._balance -= amount
def statement_line(self):
return f"{self.owner}: {self.balance}"
acc = BankAccount("Ana", 200)
acc.deposit(50)
print(acc.statement_line())
try:
acc.balance = 1000
except AttributeError as error:
print("Read-only:", error)
Press Run to see the output.
The property exposes the balance for reading while the methods remain the only way to change it. The failed assignment is the point of the exercise, not a mistake to fix.
Recap
- Methods centralise the rules for changing an object’s state.
@propertycomputes values on demand; a setter adds validation to assignment.@classmethodbuilds alternatives,@staticmethodnamespaces helpers, and both are optional.
Next, you will reuse a class through inheritance, and see where that stops being a good idea.
When should I use a property instead of a normal attribute?
Is a leading underscore private?
Progress is saved in this browser only. No account, no email.