Python Property Cheatsheet
Python Property Cheatsheet
Python Property Cheatsheet
class MyClass:
def __init__(self):
@property
def value(self):
return self._value
@value.setter
if new_value < 0:
self._value = new_value
@value.deleter
def value(self):
del self._value
- Controlled Access: Validates and controls changes to the state through methods.
Incorrect Usage:
class Counter:
def __init__(self):
Page 1
Python @property Decorator Cheatsheet
@property
def value(self):
return self._value
@value.setter
self._value = new_value
This causes infinite recursion because self.value calls the setter again.
Corrected Example:
class Counter:
def __init__(self):
@property
def value(self):
return self._value
@value.setter
if new_value < 0:
self._value = new_value
|----------------------|-----------------------|---------------------|
Page 2
Python @property Decorator Cheatsheet
- Use Private Attributes: Always use a private attribute for backing properties.
- Readability: Prefer properties for simple access; methods for complex operations.
- Avoid Side Effects: Keep property getters free of side effects to maintain predictability.
Page 3