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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
TCP/IP Model The TCP/IP model (Transmission Control Protocol/Internet Protocol) is a four-layer networking framework that enables reliable communication between devices over interconnected networks. It provides a standardized set of protocols for transmitting data across interconnected networks, ensuring efficie
7 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read