

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are Getters/Setters methods for Python Class?
Getters and setters are used in many object oriented programming languages to ensure the principle of data encapsulation. They are known as mutator methods as well. Data encapsulation is seen as the bundling of data with the methods that operate on these data. These methods are of course the getter for retrieving the data and the setter for changing the data. According to this principle, the attributes of a class are made private to hide and protect them from other code.
Unfortunately, it is widespread belief that a proper Python class should encapsulate private attributes by using getters and setters. Using getters and setters is not easy and elegant. The pythonic way to do this is to use properties or a class with property . A method which is used for getting a value is decorated with "@property". The method which has to function as the setter is decorated with "@x.setter".
Example
An example of using getters and setters is as follows
class P: def __init__(self,x): self.__set_x(x) def __get_x(self): return self.__x def __set_x(self, x): if x < 0: self.__x = 0 elif x > 1000: self.__x = 1000 else: self.__x = x x = property(__get_x, __set_x)
- Related Questions & Answers
- What are getters and setters methods in PHP?
- Getters and Setters in Kotlin
- getters and setters in JavaScript classes?
- What is the difference between Getters and Setters in JavaScript?
- What are static methods in a Python class?
- What are Class/Static methods in Java?
- What are the important methods of the SQLException class?
- What are the differences between class methods and class members in C#?
- What are the methods for generating frequent itemsets?
- What are the methods for Clustering with Constraints?
- What are base overloading methods in Python?
- What are the methods for expressing attribute test conditions?
- What are the methods for constructing an Ensemble Classifier?
- What are the clustering methods for spatial data mining?
- What are the data Mining methods for Recommender Systems?