Lesson 23 of 30

In progress

Course progress

Python

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 @property for 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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



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.
  • @property computes values on demand; a setter adds validation to assignment.
  • @classmethod builds alternatives, @staticmethod namespaces 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?
Use a property when the value is computed, or when assignment needs a rule. For a plain stored value with no rule, a normal attribute is simpler and faster.
Is a leading underscore private?
Only by convention. Nothing stops other code reading `_balance`; the underscore tells readers it is internal and may change. Python has name mangling with two underscores, but it is rarely the right tool.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.