In Python, getters and setters 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. Private variables in python are not actually hidden fields like in other object oriented languages. Getters and Setters in python are often used when:
- We use getters & setters to add validation logic around getting and setting a value.
- To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.
Using normal function to achieve getters and setters behaviour
To achieve getters & setters property, if we define normal
set() methods it will not reflect any special implementation. For Example
In above code functions
set_age() acts as normal functions and doesn’t play any impact as getters and setters, to achieve such functionality Python has a special function
Using property() function to achieve getters and setters behaviour
property()is a built-in function that creates and returns a property object. A property object has three methods, getter(), setter(), and delete().
property() function in Python has four arguments
property(fget, fset, fdel, doc),
fget is a function for retrieving an attribute value.
fset is a function for setting an attribute value.
fdel is a function for deleting an attribute value.
doc creates a docstring for attribute. A property object has three methods,
delete() to specify
fdel individually. For Example
setter method called getter method called 10
In above code there is only one print statement at
line #25 but output consists of three lines due to setter method
set_age() called in
line #23 and getter method
get_age() called in
line #25. Hence
age is a property object that helps to keep the access of private variable safe.
Using @property decorators to achieve getters and setters behaviour
In previous method we used
property() function in order to achieve getters and setters behaviour. However as mentioned earlier in this post getters and setters are also used for validating the getting and setting of attributes value. There is one more way to implement property function i.e. by using decorator. Python @property is one of the built-in decorators. The main purpose of any decorator is to change your class methods or attributes in such a way so that the user of your class no need to make any change in their code. For Example
setter method called getter method called 19
In above code it is clear that how to use
@property decorator to create getters & setters in pythonic way.
Line 15-16 acts as a validation code that raises a
ValueError if we try to initialize age with value less than 18, In this way any kind of validation can be applied in getter or setter functions .
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.
- Automate getter-setter generator for Java using Python
- Important differences between Python 2.x and Python 3.x with examples
- Creating and updating PowerPoint Presentations in Python using python - pptx
- Loops and Control Statements (continue, break and pass) in Python
- Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
- Python | Using variable outside and inside the class and method
- Releasing GIL and mixing threads from C and Python
- Python | Boolean List AND and OR operations
- Difference between 'and' and '&' in Python
- Replace the column contains the values 'yes' and 'no' with True and False In Python-Pandas
- Ceil and floor of the dataframe in Pandas Python – Round up and Truncate
- Login Application and Validating info using Kivy GUI and Pandas in Python
- Get the city, state, and country names from latitude and longitude using Python
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
Improved By : Akanksha_Rai