Python's property() class
Aman Bhardwaj
Senior Software Engineer at Query | CyberSecurity | I love building Software Stuff
As we know that in languages like Java, C++, classes are supposed to contain private data attributes as a best coding practice. That's why we need getter and setter methods for accessing and mutating those attributes i.e.. those attributes cannot be accessed directly outside of the class.
But Python doesn't have the concept of public or private attributes, though it follows a convention of naming the private attributes starting with underscore (_). For example an attribute named status will be named _status to indicate other developers that the attribute is private and to be careful while changing its value.
Let us consider an example Employee class in Python below:
Output:
DISABLED
As you can see in the above example the _status attribute, though indicated as private can be pretty much accessed outside of the class and can be mutated. But what if you really want to impose restriction on how a data attribute is set based on some use case ?? This is the problem that is solved by the built-in property() class.
Working of the property class
Let us consider the same Employee class example in the below code snippet:
领英推荐
Output:
Setter called..
Setter called..
Getter called ..
DISABLED
Let's analyse the working of above code snippet:
When should we use the property class ?
Whenever there is a restriction on the way a data attribute of a class should be set, you can consider using the built-in property class.
Additional notes:
Thank you for reading till the end and I hope you learnt something from it. Please follow me on Linkedin for more such articles on Python.