Bird
Raised Fist0
Pythonprogramming~10 mins

Property decorator usage in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Property decorator usage
Define class with private attribute
Define @property method
Access property: calls getter method
Define @property.setter method
Assign to property: calls setter method
Property value updated internally
Access property again to get updated value
The flow shows how a class uses @property to create a getter and setter for a private attribute, allowing controlled access and update.
Execution Sample
Python
class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

p = Person('Alice')
print(p.name)
p.name = 'Bob'
print(p.name)
This code creates a Person class with a private _name attribute and uses @property to get and set the name safely.
Execution Table
StepActionVariable/AttributeValueOutput
1Create Person instance with name 'Alice'p._name'Alice'
2Access p.name (calls getter)p.name'Alice'Alice
3Assign p.name = 'Bob' (calls setter)p._name'Bob'
4Access p.name again (calls getter)p.name'Bob'Bob
5End of programExecution stops
💡 Program ends after printing updated property value.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
p._nameundefined'Alice''Bob''Bob'
p.name (getter)undefined'Alice''Bob''Bob'
Key Moments - 3 Insights
Why do we use _name instead of name inside the class?
We use _name as a private attribute to avoid direct access. The property methods control how name is accessed or changed, as shown in steps 1 and 3 of the execution_table.
What happens when we assign p.name = 'Bob'?
The setter method is called, which updates the private _name attribute. This is shown in step 3 where p._name changes to 'Bob'.
Why does print(p.name) call a method instead of accessing a variable?
Because of the @property decorator, p.name calls the getter method, which returns the private _name value. This is shown in steps 2 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of p._name after step 3?
A'Bob'
B'Alice'
Cundefined
DNone
💡 Hint
Check the 'Variable/Attribute' and 'Value' columns at step 3 in execution_table.
At which step does the getter method return 'Alice'?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for when p.name is accessed and output is 'Alice' in execution_table.
If we remove the @name.setter method, what happens when we assign p.name = 'Bob'?
AIt updates p._name to 'Bob' anyway
BIt silently ignores the assignment
CIt raises an AttributeError
DIt creates a new attribute p.name
💡 Hint
Think about how property setters control assignment, and what happens if setter is missing.
Concept Snapshot
Use @property to create a getter method for a private attribute.
Use @propertyname.setter to create a setter method.
Accessing the property calls the getter.
Assigning to the property calls the setter.
This controls attribute access safely and cleanly.
Full Transcript
This visual execution shows how the property decorator works in Python. We start by creating a class with a private attribute _name. The @property decorator makes a method act like a readable attribute. When we access p.name, it calls the getter method and returns _name. The @name.setter decorator allows us to assign to p.name, which calls the setter method and updates _name. The execution table traces these steps, showing how p._name changes from 'Alice' to 'Bob'. Key moments clarify why we use a private attribute and how the getter and setter methods work. The quiz tests understanding of variable values at each step and what happens if the setter is missing.

Practice

(1/5)
1.

What does the @property decorator do in a Python class?

easy
A. It converts a function into a static method.
B. It makes a method private.
C. It allows a method to be accessed like an attribute.
D. It deletes an attribute from the class.

Solution

  1. Step 1: Understand the role of @property

    The @property decorator lets you call a method without parentheses, like an attribute.
  2. Step 2: Compare options

    Only It allows a method to be accessed like an attribute. correctly describes this behavior. Other options describe unrelated features.
  3. Final Answer:

    It allows a method to be accessed like an attribute. -> Option C
  4. Quick Check:

    @property makes method act like attribute [OK]
Hint: Remember: @property hides () making method look like attribute [OK]
Common Mistakes:
  • Thinking @property makes method private
  • Confusing @property with @staticmethod
  • Believing @property deletes attributes
2.

Which of the following is the correct syntax to define a setter for a property named value?

class MyClass:
    @property
    def value(self):
        return self._value

    # What goes here?
easy
A. @setter.value\ndef value(self, val):\n self._value = val
B. @value.setter\ndef value(self, val):\n self._value = val
C. @value.set\ndef set_value(self, val):\n self._value = val
D. @value.setter\ndef set_value(self, val):\n self._value = val

Solution

  1. Step 1: Identify correct setter syntax

    The setter uses the property name with @value.setter and defines a method with the same name value.
  2. Step 2: Check method name and decorator

    @value.setter\ndef value(self, val):\n self._value = val correctly uses @value.setter and method value. Others use wrong decorator or method names.
  3. Final Answer:

    @value.setter\ndef value(self, val):\n self._value = val -> Option B
  4. Quick Check:

    Setter uses @propertyname.setter and same method name [OK]
Hint: Setter decorator is @propertyname.setter with same method name [OK]
Common Mistakes:
  • Using @setter.value instead of @value.setter
  • Changing method name in setter
  • Using @value.set instead of @value.setter
3.

What will be the output of the following code?

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            self._radius = 0
        else:
            self._radius = value

c = Circle(5)
c.radius = -3
print(c.radius)
medium
A. 0
B. 5
C. -3
D. AttributeError

Solution

  1. Step 1: Understand setter logic

    When setting radius, if value < 0, it sets _radius to 0, else to value.
  2. Step 2: Trace code execution

    Initial radius is 5. Then c.radius = -3 triggers setter, sets _radius to 0. Printing c.radius returns 0.
  3. Final Answer:

    0 -> Option A
  4. Quick Check:

    Setter sets negative radius to 0 [OK]
Hint: Setter changes negative radius to zero, so output is 0 [OK]
Common Mistakes:
  • Expecting original value 5 to remain
  • Printing -3 instead of 0
  • Confusing property with direct attribute
4.

Find the error in this code using property decorators and fix it.

class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def set_name(self, value):
        self._name = value

p = Person('Alice')
p.name = 'Bob'
print(p.name)
medium
A. Change setter method name to name instead of set_name.
B. Remove the @property decorator.
C. Change self._name to self.name in setter.
D. Add a deleter method for name.

Solution

  1. Step 1: Identify setter method name mismatch

    The setter decorator @name.setter requires the method to be named name, but here it is set_name.
  2. Step 2: Fix method name

    Rename the setter method to name to match the property name and decorator.
  3. Final Answer:

    Change setter method name to name instead of set_name. -> Option A
  4. Quick Check:

    Setter method name must match property name [OK]
Hint: Setter method name must match property name exactly [OK]
Common Mistakes:
  • Using different method name for setter
  • Removing @property decorator mistakenly
  • Changing attribute name inside setter
5.

Consider a class that stores a temperature in Celsius internally but exposes it as Fahrenheit using property decorators. Which code correctly implements this?

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        # Convert Celsius to Fahrenheit
        return (self._celsius * 9/5) + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        # Convert Fahrenheit to Celsius
        self._celsius = (value - 32) * 5/9

# Usage
temp = Temperature(0)
temp.fahrenheit = 212
print(round(temp._celsius))

What is the output?

hard
A. 32
B. 212
C. 0
D. 100

Solution

  1. Step 1: Understand property getter and setter

    The getter converts Celsius to Fahrenheit. The setter converts Fahrenheit back to Celsius and stores it.
  2. Step 2: Trace the code

    Initially, Celsius is 0. Setting temp.fahrenheit = 212 calls setter, converts 212°F to Celsius: (212-32)*5/9 = 100. Printing temp._celsius rounded gives 100.
  3. Final Answer:

    100 -> Option D
  4. Quick Check:

    Setter converts Fahrenheit to Celsius correctly [OK]
Hint: Setter converts Fahrenheit to Celsius, so 212°F = 100°C [OK]
Common Mistakes:
  • Confusing getter and setter conversions
  • Printing Fahrenheit instead of Celsius
  • Not rounding the output