Now the requirement is the values of age and salary attributes should be positive.
- Add a comment:.
- Maximum Influence: The 12 Universal Laws of Power.
- Introduction to Python descriptors – IBM Developer.
Note that the same logic codes of checking positive value appear twice, respectively in age setter and salary setter. Then use the created PositiveAttr descriptor to define attributes in the Employee class.
The PositiveAttr descriptor will ensure the value of attributes are positive. Both age and salary are objects of the PositiveAttr descriptor.
Attribute Descriptors - Fluent Python [Book]
They share the common codes to to do value validation. For example, obj.
It can also directly be invoked by method name i. Descriptor Example : In this Example a data descriptor sets and returns values normally and prints a message logging their access.
Code Creating a Descriptor using property : property , it is easy to create a usable descriptor for any attribute. Syntax for creating property.
This method is used when the same descriptor is needed across many different classes and attributes, for example, for type validation. Creating a Descriptor using property Decorator : In this we use the power of property decorators which are a combination of property type method and Python decorators. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.
- Coding is my Craft;
- The One Word You Need To Remember: Property!
- Embracing Soul Care: Making Space for What Matters Most?
See your article appearing on the GeeksforGeeks main page and help other Geeks. Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Python descriptors made simple
Writing code in comment? Please use ide. Python program showing.