The property decorator lets you use methods like attributes. It helps keep your code clean and easy to use.
Property decorator usage in Python
Start learning this pattern below
Jump into concepts and practice - no test required
class ClassName: @property def attribute(self): # code to get the value pass @attribute.setter def attribute(self, value): # code to set the value pass @attribute.deleter def attribute(self): # code to delete the value pass
The @property decorator makes a method act like a read-only attribute.
Use @attribute.setter to allow changing the attribute value.
name. You can get the name but not change it directly.class Person: def __init__(self, name): self._name = name @property def name(self): return self._name
class Person: def __init__(self, age): self._age = age @property def age(self): return self._age @age.setter def age(self, value): if value < 0: raise ValueError("Age cannot be negative") self._age = value
This program creates a rectangle with width and height. It uses properties to get and set width and height safely. The area is a read-only property calculated from width and height.
class Rectangle: def __init__(self, width, height): self._width = width self._height = height @property def area(self): return self._width * self._height @property def width(self): return self._width @width.setter def width(self, value): if value <= 0: raise ValueError("Width must be positive") self._width = value @property def height(self): return self._height @height.setter def height(self, value): if value <= 0: raise ValueError("Height must be positive") self._height = value rect = Rectangle(4, 5) print(f"Area: {rect.area}") rect.width = 10 print(f"New area: {rect.area}")
Properties let you change how attributes work without changing how you use them.
Use a leading underscore (like _width) to mark internal variables that should not be accessed directly.
Trying to set a read-only property without a setter will cause an error.
The @property decorator makes methods behave like attributes.
You can add setters and deleters to control how attributes are changed or removed.
Properties help keep your class interface simple and safe.
Practice
What does the @property decorator do in a Python class?
Solution
Step 1: Understand the role of
The@property@propertydecorator lets you call a method without parentheses, like an attribute.Step 2: Compare options
Only It allows a method to be accessed like an attribute. correctly describes this behavior. Other options describe unrelated features.Final Answer:
It allows a method to be accessed like an attribute. -> Option CQuick Check:
@property makes method act like attribute [OK]
- Thinking @property makes method private
- Confusing @property with @staticmethod
- Believing @property deletes attributes
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?Solution
Step 1: Identify correct setter syntax
The setter uses the property name with@value.setterand defines a method with the same namevalue.Step 2: Check method name and decorator
@value.setter\ndef value(self, val):\n self._value = val correctly uses@value.setterand methodvalue. Others use wrong decorator or method names.Final Answer:
@value.setter\ndef value(self, val):\n self._value = val -> Option BQuick Check:
Setter uses @propertyname.setter and same method name [OK]
- Using @setter.value instead of @value.setter
- Changing method name in setter
- Using @value.set instead of @value.setter
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)Solution
Step 1: Understand setter logic
When settingradius, if value < 0, it sets_radiusto 0, else to value.Step 2: Trace code execution
Initial radius is 5. Thenc.radius = -3triggers setter, sets_radiusto 0. Printingc.radiusreturns 0.Final Answer:
0 -> Option AQuick Check:
Setter sets negative radius to 0 [OK]
- Expecting original value 5 to remain
- Printing -3 instead of 0
- Confusing property with direct attribute
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)Solution
Step 1: Identify setter method name mismatch
The setter decorator@name.setterrequires the method to be namedname, but here it isset_name.Step 2: Fix method name
Rename the setter method tonameto match the property name and decorator.Final Answer:
Change setter method name tonameinstead ofset_name. -> Option AQuick Check:
Setter method name must match property name [OK]
- Using different method name for setter
- Removing @property decorator mistakenly
- Changing attribute name inside setter
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?
Solution
Step 1: Understand property getter and setter
The getter converts Celsius to Fahrenheit. The setter converts Fahrenheit back to Celsius and stores it.Step 2: Trace the code
Initially, Celsius is 0. Settingtemp.fahrenheit = 212calls setter, converts 212°F to Celsius: (212-32)*5/9 = 100. Printingtemp._celsiusrounded gives 100.Final Answer:
100 -> Option DQuick Check:
Setter converts Fahrenheit to Celsius correctly [OK]
- Confusing getter and setter conversions
- Printing Fahrenheit instead of Celsius
- Not rounding the output
