- Aliases
- and operator
- Arrays
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Filter()
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Property()
- Random module
- range() function
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python property()
: Syntax, Usage, and Examples
The property()
function in Python lets you manage how class attributes are accessed and modified. Instead of calling explicit getter or setter methods, you can create attributes that behave like regular variables but include custom logic behind the scenes. This gives your code clarity without losing control.
How to Use the Python property()
Function
You can create a property using either the property()
function or the @property
decorator.
Syntax Using the property()
Function
class Example:
def __init__(self):
self._value = 0
def get_value(self):
return self._value
def set_value(self, new_value):
self._value = new_value
value = property(get_value, set_value)
This defines a value
attribute with custom getter and setter methods. The property()
call ties them together.
Syntax Using the @property
Decorator
class Example:
def __init__(self):
self._value = 0
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value
This approach is more common in modern Python and easier to read.
When to Use property()
in Python
Use the Python property function when you:
- Want to control access to a class attribute without changing how it’s used.
- Need to run logic when an attribute is read or updated.
- Prefer cleaner syntax over calling getter/setter methods.
- Want to validate or transform values before storing them.
These cases are common in applications that rely on clean interfaces or enforce strict rules for internal state.
Examples of Python Property in Action
Simple Getter and Setter
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
if not new_name:
raise ValueError("Name cannot be empty")
self._name = new_name
user = Person("Maya")
print(user.name) # Output: Maya
user.name = "Sam"
This pattern lets you treat name
like a variable, but with validation baked in.
Read-Only Property
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9/5 + 32
t = Temperature(0)
print(t.fahrenheit) # Output: 32.0
You get a derived value as a regular attribute without exposing a setter.
Write-Only Property
class PasswordManager:
def __init__(self):
self._hashed_password = None
@property
def password(self):
raise AttributeError("Password is write-only")
@password.setter
def password(self, plain_text):
self._hashed_password = hash(plain_text)
manager = PasswordManager()
manager.password = "mysecret"
This is useful when storing sensitive data like passwords.
Learn More About Python Properties
property() vs property decorator
Both property()
and @property
achieve the same goal. The decorator syntax is preferred for readability. The manual property()
function is useful when you're defining multiple properties dynamically or want more control.
# Using property()
class Demo:
def __init__(self):
self._value = 0
def get_value(self):
return self._value
def set_value(self, val):
self._value = val
value = property(get_value, set_value)
Python Property Setter and Getter Naming
Keep getter/setter method names consistent. Using the same name across the property, getter, and setter maintains clarity:
@property
def count(self):
return self._count
@count.setter
def count(self, value):
self._count = value
Avoid unrelated names like get_count()
and modify_count()
unless you’re using the property()
function explicitly.
Cached Property in Python
You can improve performance with functools.cached_property
. It caches the result of a method the first time it’s accessed:
from functools import cached_property
class Circle:
def __init__(self, radius):
self.radius = radius
@cached_property
def area(self):
print("Calculating area...")
return 3.14 * self.radius ** 2
c = Circle(5)
print(c.area) # Calculates once
print(c.area) # Uses cached result
This is useful for expensive calculations that don’t need to rerun unless the state changes.
Abstract Property in Python
You can define abstract properties in base classes using the abc
module:
from abc import ABC, abstractmethod
class Animal(ABC):
@property
@abstractmethod
def sound(self):
pass
Subclasses must implement the sound
property, ensuring a consistent interface.
Python Properties in Data Classes
With Python 3.8+, data classes can use properties too:
from dataclasses import dataclass
@dataclass
class Item:
_price: float
@property
def price(self):
return round(self._price, 2)
item = Item(12.3456)
print(item.price) # Output: 12.35
This allows formatting, conversion, or validation on access.
Check If Property Exists in Python
To see if an attribute is a property, use:
isinstance(type(obj).__dict__["attr_name"], property)
Or, catch an AttributeError
when accessing properties that aren't set.
Real-World Use Cases
Form Validation
When building forms, properties help you validate data before saving it:
class Form:
def __init__(self):
self._email = ""
@property
def email(self):
return self._email
@email.setter
def email(self, value):
if "@" not in value:
raise ValueError("Invalid email")
self._email = value
Data Transformation
Transform and store data behind the scenes without changing the public interface:
class Order:
def __init__(self, amount):
self._amount = amount
@property
def tax(self):
return self._amount * 0.2
Simplify APIs
Libraries use properties to provide simpler interfaces without exposing internal methods.
Best Practices for Using Python Properties
- Use properties for clean syntax, not just because you can.
- Only add logic when you need to validate, transform, or compute on access.
- Keep properties fast—don’t hide long computations behind them unless cached.
- Combine with
@classmethod
or@staticmethod
only when it makes sense.
The Python property function lets you create smart attributes that look like variables but act like functions. Whether you want to add validation, lazy calculations, or restrict access, properties give you the flexibility to keep your class interface clean and intuitive.
You can use the Python property decorator for readability, or stick with the base function if you're building classes dynamically. Either way, understanding properties in Python helps you write more maintainable, professional code.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.