Video courses for company/skill based Preparation
Purchase mock tests for company/skill building
Getters and Setters in Python
Getters and Setters in Python:
Getters and setters in python are not the same as those in other object-oriented programming languages. Basically, the main purpose of using getters and setters in object-oriented programs is to ensure data encapsulation.
When to Use :
- We use getters and setters to add validation logic for getting and setting a value.
- To avoid direct access to a class field, private variables cannot be accessed directly or modified by any external user.
User-Defined getter and setter:
Property Function for getter and setter:
- Property() is a built-in function that creates and returns a property object in Python.
- It has three methods:-
property(fget, fset, fdel, doc)
fget() – used to get the value of attribute
fset() – used to set the value of attribute
fdel() – used to delete the attribute value
doc() – string that contains the documentation (docstring) for the attribute
Return: Returns a property attribute from the given getter, setter and deleter.