CodeBlanks Logo Icon CodeBlanks

@property

Learn to define properties with @property.

The @property decorator

The @property decorator turns a method into something readable like an attribute. You access it without parentheses; this gives the outside a clean encapsulated look.

Example: class Account:\n @property\n def balance(self):\n return self._balance. Writing a.balance calls the method; not a.balance(). This makes it easy to update the inner logic later without changing how outside code accesses it; you can add computation, for instance.

Access without parentheses

A method marked with @property is called without parentheses. Writing a.balance is enough; a.balance() raises an error. This hides the difference between an attribute and a computed value from the outside.

So today it returns self._balance; tomorrow it can do a computation, while outside code stays unchanged. This is the core of encapsulation: stable outer interface, flexible inner data. Example: return self._balance * self._rate.

Practice Add @property to Account

Define the Account class. Add def __init__(self, balance): with self._balance = balance in the body. Above add the @property decorator and a method def balance(self):; in its body write return self._balance. Then create an instance with a = Account(100) and call print(a.balance).

Starter code

main.py
# Add a property to the Account class

Sample solution

main.py
# Define the Account class with @property
class Account:
    def __init__(self, balance):
        self._balance = balance
    @property
    def balance(self):
        return self._balance

a = Account(100)
print(a.balance)

Expected output

100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the @property line

Question
    ____
    def balance(self):
        return self._balance
Answer
    @property
    def balance(self):
        return self._balance

Explanation: The @property decorator turns the method into a readable attribute.

2 What does @property do?

  • It deletes an attribute
  • It creates a class variable
  • It makes a method read like an attribute Correct answer
  • It makes a method static

Explanation: @property makes a method read like an attribute; no parentheses needed.

3 Match the @property concepts

Term Meaning
@property Getter decorator
a.balance Parenthesis-free access
self._balance Inner data

All lessons in Intermediate