0% found this document useful (0 votes)
11 views

Python Property Cheatsheet

cheatsheet on python property decorator
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Property Cheatsheet

cheatsheet on python property decorator
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python @property Decorator Cheatsheet

1. Using @property with Getter, Setter, and Deleter

class MyClass:

def __init__(self):

self._value = None # Private attribute

@property

def value(self):

"""Getter for value."""

return self._value

@value.setter

def value(self, new_value):

"""Setter for value."""

if new_value < 0:

raise ValueError('Value must be non-negative')

self._value = new_value

@value.deleter

def value(self):

"""Deleter for value."""

del self._value

2. Importance of Private Attributes

Why Use Private Attributes?

- Encapsulation: Hides the internal state of an object.

- Controlled Access: Validates and controls changes to the state through methods.

Infinite Recursion Problem Example

Incorrect Usage:

class Counter:

def __init__(self):

Page 1
Python @property Decorator Cheatsheet

self.value = 0 # Incorrectly accessing the property

@property

def value(self):

return self._value

@value.setter

def value(self, new_value):

self._value = new_value

This causes infinite recursion because self.value calls the setter again.

Corrected Example:

class Counter:

def __init__(self):

self._value = 0 # Use private attribute

@property

def value(self):

return self._value

@value.setter

def value(self, new_value):

if new_value < 0:

raise ValueError('Must be non-negative')

self._value = new_value

3. Accessing Properties vs. Regular Methods

| Feature | Property Access | Method Call |

|----------------------|-----------------------|---------------------|

| Syntax | obj.value | obj.get_value() |

| Mutability | obj.value = 10 | obj.set_value(10) |

Page 2
Python @property Decorator Cheatsheet

| Readability | More intuitive | Slightly verbose |

| Control over access | Uses decorators | Standard methods |

4. Best Practices & Tips

- Use Private Attributes: Always use a private attribute for backing properties.

- Validate Input: Ensure setters validate data to maintain integrity.

- Readability: Prefer properties for simple access; methods for complex operations.

- Avoid Side Effects: Keep property getters free of side effects to maintain predictability.

- Documentation: Document getters/setters to clarify their purpose and constraints.

Page 3

You might also like