Computer >> Computer tutorials >  >> Programming >> Python

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)