Python property() Function
The property() function in Python is used to create managed attributes in object-oriented programming. It lets you define methods that act like attributes – helpful for adding logic when accessing or updating a value.
Syntax
property(fget=None, fset=None, fdel=None, doc=None)
Parameters:
fget– Function to get the value (getter)fset– Function to set the value (setter)fdel– Function to delete the value (deleter)doc– Optional docstring
Returns:
- A property object that can be assigned to a class attribute
Example: Basic Usage of property()
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
print("Getting name...")
return self._name
def set_name(self, value):
print("Setting name...")
self._name = value
def del_name(self):
print("Deleting name...")
del self._name
name = property(get_name, set_name, del_name)
Usage:
p = Person("Alice")
print(p.name) # Getting name... → Alice
p.name = "Bob" # Setting name...
print(p.name) # Getting name... → Bob
del p.name # Deleting name...
Modern Alternative: Using @property Decorator
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
print("Getting name...")
return self._name
@name.setter
def name(self, value):
print("Setting name...")
self._name = value
@name.deleter
def name(self):
print("Deleting name...")
del self._name
Getting name...
Setting name...
Deleting name...
Why Use property()?
- Encapsulation: Control how attributes are accessed or modified
- Cleaner syntax: Looks like direct attribute access
- Backward compatibility: Add logic without changing the API
Common Mistakes
- Not using the underscore convention (e.g.,
_name) for internal variables - Using
property()without definingfget– it won’t be readable - Using property incorrectly inside
__init__
Interview Tip
Interviewers often ask about encapsulation and data hiding. Showing that you know how to use property and @property in Python can demonstrate your grasp of object-oriented principles.
Summary
property()lets you control access to attributes in classes.- You can use
fget,fset,fdelto manage how values are accessed, set, or deleted. - The
@propertydecorator is a modern and cleaner alternative.
Practice Problem
Create a class Temperature with a Celsius attribute. Use @property to add a computed Fahrenheit property (read-only).
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return (self._celsius * 9/5) + 32
t = Temperature(25)
print(t.fahrenheit) # Output: 77.0
Comments
Loading comments...