Property Decorators
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 14 of 64.
Property decorators let you control how attributes are accessed and modified, while keeping the simple attribute syntax.
Here is an example of a class with a property getter:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def age(self):
return self._ageUse the property like a regular attribute:
person = Person("Alice", 30)
print(person.age)Output:
30Notice you access age without parentheses, even though it's actually calling a method.
Add a setter to validate data when setting values:
class Person:
def __init__(self, name, age):
self._name = name
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 = valueNow you can set the age with automatic validation:
person = Person("Alice", 30)
person.age = 31 # Uses the setter with validation
print(person.age) # Uses the getter
# This would raise an error:
# person.age = -5 # ValueError: Age cannot be negativeOutput:
31Create computed properties that calculate values:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
rect = Rectangle(5, 3)
print(rect.area) # Calculates 5 * 3 = 15Output:
15Key Point: Property decorators make methods look like attributes. Use @property for getters and @attribute_name.setter for setters. This allows data validation and computed values while keeping simple attribute access syntax.
Challenge
MediumComplete the Temperature class in temperature.py that converts between Celsius and Fahrenheit. Then use this class in driver.py to test temperature conversions. Follow the TODO comments in both files for step-by-step instructions.
Cheat sheet
Property decorators let you control how attributes are accessed and modified while keeping simple attribute syntax.
Use @property for getter methods:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def age(self):
return self._age
person = Person("Alice", 30)
print(person.age) # Access like an attribute, no parenthesesUse @attribute_name.setter for setter methods with validation:
class Person:
def __init__(self, name, age):
self._name = name
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
person = Person("Alice", 30)
person.age = 31 # Uses setter with validationCreate computed properties that calculate values:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
rect = Rectangle(5, 3)
print(rect.area) # Calculates 5 * 3 = 15Try it yourself
# TODO: Import the Temperature class from the temperature module
# Test the class:
# TODO: Create a temperature instance at 25°C
temp = None # Replace with actual Temperature instance
# TODO: Print both Celsius and Fahrenheit values
# TODO: Use the format: "25.0°C is 77.0°F"
# TODO: Set the temperature to 98.6°F
# TODO: Print both values again to confirm the conversion works
# TODO: Use the same format as beforeThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes