Python property() function
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
OutputGetting 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
OutputGetting 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. Using property() 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
OutputGetting 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.
Similar Reads
Python open() Function
The Python open() function is used to open internally stored files. It returns the contents of the file as Python objects. Python open() Function SyntaxThe open() function in Python has the following syntax: Syntax: open(file_name, mode) Parameters: file_name: This parameter as the name suggests, is
3 min read
pow() Function - Python
pow() function in Python is a built-in tool that calculates one number raised to the power of another. It also has an optional third part that gives the remainder when dividing the result. Example: [GFGTABS] Python print(pow(3,2)) [/GFGTABS]Output9 Explanation: pow(3, 2) calculates 32 = 9, where the
2 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
Python oct() Function
Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python. Python oct() Function SyntaxSyntax : oct(x) Parameters: x - Must be an integer number and can be in either binary, decimal
2 min read
__import__() function in Python
__import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those mo
2 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
4 min read
Python len() Function
The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example: [GFGTABS] Python s = "G
2 min read
Python map() function
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '
4 min read
ord() function in Python
Python ord() function returns the Unicode code of a given single character. It is a modern encoding standard that aims to represent every character in every language. Unicode includes: ASCII characters (first 128 code points)Emojis, currency symbols, accented characters, etc.For example, unicode of
2 min read
Python 3 - input() function
In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optio
3 min read