Difference between attributes and properties in Python
Class Attribute: Class Attributes are unique to each class. Each instance of the class will have this attribute.
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.
Now, Let’s see an example on properties:
1) Create Properties of a class using property() function:
Syntax: property(fget, fset, fdel, doc)
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.
Getting value happy Coding Setting value to Hey Coder! Deleting value
Table of difference between Attribute V/s Property
|Attributes are described by data variables for example like name, age, height etc.||Properties are special kind of attributes.|
Two types of attributes:
|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.|
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course