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.

Python3




# 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)


Output

1
2
2



Python property(): Returns object of the property class. In this example, we are demonstrating the use of property() function.

Python3




# 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


Output

Getting 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

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.

Similar Reads

Python property() Function Syntax

Python property() function is used to create a class property in Python....

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 vs Attribute

...