Python property() function (original) (raw)
Last Updated : 15 Mar, 2025
**property() function in Python is a built-in function that returns an object of the property class. It allows developers to create properties within a class, providing a way to control access to an attribute by defining getter, setter and deleter methods. This enhances encapsulation and ensures better control over class attributes. Example:
Python `
class Student: def init(self, name): self._name = name
name = property(lambda self: self._name)
s = Student("shakshi") print(s.name)
`
**Explanation: Student class initializes _name in **__init__. The **property() function with a lambda defines a read-only name property, restricting modifications. **print(s.name) accesses and prints _name.
Syntax of property()
property(fget=None, fset=None, fdel=None, doc=None)
Here none is the default value if a getter, setter or deleter is not provided.
**Parameters:
- **fget() used to get the value of attribute.
- **fset() used to set the value of attribute.
- **fdel() used to delete the attribute value.
- **doc() string that contains the documentation (docstring) for the attribute.
**Return: Returns a property object from the given getter, setter and deleter.
**Note:
- If no arguments are given, **property() method returns a base property attribute that doesn’t contain any getter, setter or deleter.
- If doc isn’t provided, property() method takes the docstring of the getter function.
Creating properties in Python
We can create properties using two methods:
- Using the property() function
- Using the @property decorator
Using the property() function
Python `
class Alphabet: def init(self, value): self._value = value
def getValue(self):
print("Getting value")
return self._value
def setValue(self, value):
print("Setting value to " + value)
self._value = value
def delValue(self):
print("Deleting value")
del self._value
value = property(getValue, setValue, delValue)
Usage
x = Alphabet("GeeksforGeeks") print(x.value)
x.value = "GfG" del x.value
`
Output
Getting value GeeksforGeeks Setting value to GfG Deleting value
**Explanation: Alphabet class uses the **property function to manage a private attribute _value with getter, setter and deleter methods. The **__init__ method initializes _value. **getValue retrieves and prints it, setValue updates and prints the change and delValue deletes it with a message. Accessing x.value calls **getValue, assigning a new value calls **setValue and deleting it calls **delValue.
Using the @property Decorator
Python `
class Alphabet: def init(self, value): self._value = value
@property
def value(self):
print("Getting value")
return self._value
@value.setter
def value(self, value):
print("Setting value to " + value)
self._value = value
@value.deleter
def value(self):
print("Deleting value")
del self._value
Usage
x = Alphabet("Peter") print(x.value)
x.value = "Diesel" del x.value
`
Output
Getting value Peter Setting value to Diesel Deleting value
Explanation: Alphabet class uses the @property decorator to manage _value with getter, setter and deleter methods. The getter prints “Getting value” and returns _value, the setter updates it with a message and the **deleter removes it while printing “Deleting value.” Creating an instance with “Peter” triggers the getter on **print(x.value), setting “Diesel” calls the setter and del **x.value invokes the deleter.
Python Property vs Attribute
Understanding the difference between **properties and **attributes in Python is important for writing clean, maintainable code. Properties provide controlled access to instance attributes, while attributes are direct data members of a class or instance.
A **property allows encapsulation by defining custom logic for getting, setting and deleting values. This helps in implementing validation and computed attributes dynamically. In contrast, **class attributes are shared among all instances of a class and are typically used for static data that should not be changed on an instance level.
**Example 1. class attributes vs Instances attribute
Python `
class Employee: count = 0 # Class attribute
def increase(self):
Employee.count += 1
Usage
emp1 = Employee() emp1.increase() print(emp1.count)
emp2 = Employee() emp2.increase() print(emp2.count) print(Employee.count)
`
**Explanation: Employee class has a shared class attribute count, initialized to 0. The increase method increments count. Calling **increase() on **emp1 sets count to 1 and on **emp2, it updates to 2. Printing **emp1.count, **emp2.count and **Employee.count all return 2.
**Example 2. Usingproperty() for encapsulation
Python `
class GFG: def init(self, value): self._value = value
def getter(self):
print("Getting value")
return self._value
def setter(self, value):
print("Setting value to " + value)
self._value = value
def deleter(self):
print("Deleting value")
del self._value
value = property(getter, setter, deleter)
Usage
x = GFG("Happy Coding!") print(x.value)
x.value = "Hey Coder!" del x.value
`
Output
Getting value Happy Coding! Setting value to Hey Coder! Deleting value
**Explanation: GFG class uses property to **manage _value with getter, setter and deleter methods. The getter retrieves _value, the **setter updates it and the deleter removes it, each with a message. Creating an instance with “Happy Coding!”, **print(x.value) calls the getter, assigning “Hey Coder!” **updates _value and del **x.value deletes it.
**Difference Table: Class attribute vs property
Feature | class attribute | property() |
---|---|---|
Definition | Shared across all instances of the class. | Manages instance attributes with getter, setter, and deleter. |
Modification | Changes affect all instances. | Controls access to instance attributes. |
Encapsulation | No encapsulation, direct modification. | Provides controlled access using methods. |
Usage | Used for static values across instances. | Used for dynamic control over instance attributes. |
Applications of property()
- **Encapsulation: Controls attribute access by adding logic to getters and setters.
- **Validation: Enables validation checks before assigning values.
- **Backward Compatibility: Allows modifying class implementation without breaking existing client code.
- **Computation on Access: Properties can compute values dynamically when accessed.