Python property() function
Last Updated :
03 Jul, 2024
Python property() function returns the object of the property class and it is used to create the property of a class. In Python, the property() function is a built-in function that allows us to create a property for a class. In this article, we will learn more about the Python property() function.
Python property() Function Syntax
Python property() function is used to create a class property in Python.
Syntax: property(fget, fset, fdel, doc)
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 attribute 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.
What is property() Function in Python
Python property() function is a built-in function that allows us to create a special type of attribute called a property for a class. Properties are used to encapsulate the access to an object attribute and to add some logic to the process such as computation, access control, or validation.
Python property() Function Methods
Below are the ways by which we can create property for a class in Python:
- Using property() method
- Using @property decorator
Using property() Method
In this example, we are using the property() function to create a class property in Python. We define a class called Alphabet, and within this class, we create a property named value to encapsulate access to an internal attribute _value. This property allows us to control how the _value attribute is accessed and modified by providing custom getter and setter methods.
Python
# Python program to explain property() function
# Alphabet class
class Alphabet:
def __init__(self, value):
self._value = value
# getting the values
def getValue(self):
print('Getting value')
return self._value
# setting the values
def setValue(self, value):
print('Setting value to ' + value)
self._value = value
# deleting the values
def delValue(self):
print('Deleting value')
del self._value
value = property(getValue, setValue,
delValue, )
# passing the value
x = Alphabet('GeeksforGeeks')
print(x.value)
x.value = 'GfG'
del x.value
OutputGetting value
GeeksforGeeks
Setting value to GfG
Deleting value
Using @property Decorator
The main work of decorators is they are used to add functionality to the existing code. Also called metaprogramming, as a part of the program tries to modify another part of the program at compile time. First, specify that value() method is also an attribute of Alphabet then, we use the attribute value to specify the Python property setter and the deleter. Notice that the same method value() is used with different definitions for defining the getter, setter, and deleter. Whenever we use x.value, it internally calls the appropriate getter, setter, and deleter.
Python
# Python program to explain property()
# function using decorator
class Alphabet:
def __init__(self, value):
self._value = value
# getting the values
@property
def value(self):
print('Getting value')
return self._value
# setting the values
@value.setter
def value(self, value):
print('Setting value to ' + value)
self._value = value
# deleting the values
@value.deleter
def value(self):
print('Deleting value')
del self._value
# passing the value
x = Alphabet('Peter')
print(x.value)
x.value = 'Diesel'
del x.value
OutputGetting value
Peter
Setting value to Diesel
Deleting value
Python Property vs Attribute
Class Attribute: Class Attributes are unique to each class. Each instance of the class will have this attribute. In the given example, the count variable is a class attribute.
Python
# declare a class
class Employee:
# class attribute
count = 0
# define a method
def increase(self):
Employee.count += 1
# create an Employee
# class object
a1 = Employee()
# calling object's method
a1.increase()
# print value of class attribute
print(a1.count)
a2 = Employee()
a2.increase()
print(a2.count)
print(Employee.count)
Python property(): Returns object of the property class. In this example, we are demonstrating the use of property() function.
Python
# create a class
class gfg:
# constructor
def __init__(self, value):
self._value = value
# getting the values
def getter(self):
print('Getting value')
return self._value
# setting the values
def setter(self, value):
print('Setting value to ' + value)
self._value = value
# deleting the values
def deleter(self):
print('Deleting value')
del self._value
# create a properties
value = property(getter, setter, deleter, )
# create a gfg class object
x = gfg('Happy Coding!')
print(x.value)
x.value = 'Hey Coder!'
# deleting the value
del x.value
OutputGetting value
Happy Coding!
Setting value to Hey Coder!
Deleting value
Applications
By using property() method, we can modify our class and implement the value constraint without any change required to the client code. So that the implementation is backward compatible.
Python property() function – FAQs
What is property vs attribute in Python?
- Attribute: An attribute in Python is a variable that is associated with an object. Attributes store data or state for an object. For example,
self.name in a class is an attribute. - Property: A property is a special kind of attribute that allows you to define methods to get, set, or delete its value while still using attribute-like access. Properties provide a way to manage the access to private variables.
What is the difference between a property and a method in Python?
Property: A property is accessed like an attribute but can have getter, setter, and deleter methods to control access to an underlying attribute.
Method: A method is a function defined within a class and can be called on an instance of that class.
Should I use property or method?
Use properties when you want to manage access to an attribute in a controlled manner, but still want to use attribute-like syntax. Use methods when you need to perform operations or actions that don’t directly relate to accessing or setting an attribute.
When to use properties in class?
Use properties in a class when:
- You need to add validation logic when getting or setting an attribute.
- You want to encapsulate access to an attribute.
- You want to compute an attribute on the fly without changing the way it is accessed.
What is the type of property in Python?
The type of a property in Python is <class 'property'>. You can check the type using the type() function.
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
p = Person("Alice")
print(type(Person.name)) # Output: <class 'property'>
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
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modu
2 min read
hypot() function - Python
math.hypot() function in Python is used to compute the Euclidean distance from the origin (0, 0) to a point (x, y) in a 2D plane. It calculates the hypotenuse of a right triangle, given the lengths of the two other sides. Example[GFGTABS] Python import math x = 3 y = 4 res = math.hypot(x, y) print(r
4 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
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
len() function returns number of items in an object that can be characters, words, or elements in a sequence. Letâs start with a simple example to understand the len() functions with strings: [GFGTABS] Python s = "GeeksforGeeks" # Use len() to find the length of the string length = len(s)
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 from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode c
3 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