- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- 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".
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)
- What are getters and setters methods in PHP?
- Getters and Setters in Kotlin
- What are static methods in a Python class?
- What are Class/Static methods in Java?
- What are the differences between class methods and class members in C#?
- What are the important methods of the SQLException class?
- What is difference between self and __init__ methods in python Class?
- What are the various methods available under Select class in Selenium?
- What are base overloading methods in Python?
- What are the methods for generating frequent itemsets?
- What are the methods for Clustering with Constraints?
- What are the methods and properties of the Thread class in C#?
- What are new methods added to the String class in Java 9?
- What is Regex class and its class methods in C#?