Difference between attributes and properties in Python
Last Updated :
20 Aug, 2020
Class Attribute: Class Attributes are unique to each class. Each instance of the class will have this attribute.
Example:
Python3
class Employee:
count = 0
def increase(self):
Employee.count += 1
a1 = Employee()
a1.increase()
print(a1.count)
a2 = Employee()
a2.increase()
print(a2.count)
print(Employee.count)
|
Output:
1
2
2
In the above example, count variable is a class attribute.
Instance Attribute: Instance Attributes are unique to each instance, (an instance is another name for an object). Every object/instance has its own attribute and can be changed without affecting other instances.
Example:
Python3
class Employee:
def __init__(self):
self.name = 'Gfg'
self.salary = 4000
def show(self):
print(self.name)
print(self.salary)
x = Employee()
x.show()
|
Output:
Gfg
4000
Now, Let’s see an example on properties:
1) Create Properties of a class using property() function:
Syntax: property(fget, fset, fdel, doc)
Example:
Python3
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, )
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
2) Create Properties of a class Using @property decorator:
We can apply the property function by using @property decorator. This is one of the built-in decorators. A decorator is simply a function that takes another function as an argument and adding to its behavior by wrapping it.
Example:
Python3
class byDeco:
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
x = byDeco('happy Coding')
print(x.value)
x.value = 'Hey Coder!'
del x.value
|
Output:
Getting value
happy Coding
Setting value to Hey Coder!
Deleting value
Table of difference between Attribute V/s Property
|
Attribute
|
Property
|
| Attributes are described by data variables for example like name, age, height etc. |
Properties are special kind of attributes. |
|
Two types of attributes:
- Class attribute
- Instance attribute
|
It has getter, setter and delete methods like __get__, __set__ and __delete__ methods. |
| Class attributes are defined in the class body parts usually at the top. |
We can define getters, setters, and delete methods with the property() function. |
| Instance attribute are defined in the class body using self keyword usually it the __init__() method. |
If we just want to the read property, there is also a @property decorator which you can add above your method. |