top of page

Property Decorators - Setters, Getters, and Deleters

Updated: Feb 10, 2023

In many object-oriented programming languages, data within an object can be explicitly hidden from external access by using specific keywords such as private or protected. This prevents misuse by not allowing access to the data from object.


Private and Protected Attributes


All attributes (data in object) in python classes are publicly accessible. Therefore, you don't have explicit control over data access. Using naming conventions by having one underscore as a prefix for protected attributes and two underscores for private attributes. As it is just naming convention showing the intention, users can still access attributes externally even after the naming conventions properly applied.

Python performs name mangling on private attributes. Every member with a double underscore will be changed to object._class__variable.


So, a responsible programmer, upon seeing an attribute with such a naming convention, would refrain from accessing it outside its scope.


Why Properties

@property decorator will define a setter, getter, and deleter methods. These special methods dictate how others should set, get, and delete attributes in a controlled way.


@property decorator defines a getter method, properties are accessed like an attribute, it cannot be called like a method.



@propertyname.setter decorator defines a setter method. It is used to set a value to the attribute.


@propertyname.deleter decorator defines a deleter, it is used to delete any attribute.

 
Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark

Recent Posts

See All

コメント

5つ星のうち0と評価されています。
まだ評価がありません

評価を追加
bottom of page