Detailed explanation of the use of python getter and setter methods

The main contents of this paper are as follows:
  • Explain how setter s and getter s are used
  • Explain the wonderful use of @ property decorator

    In python, setter and getter methods are not like those in other programming languages. Basically, in object-oriented programming language, the main purpose of using setter and getter methods is to ensure the encapsulation of data. Unlike other object-oriented programming languages, private variables in python are not really hidden fields. In python, setter and getter methods are usually used in the following cases:

  • Use setter and getter methods to add validation logic when getting or setting property values

Using ordinary functions to implement setter and getter methods
To implement the setter and getter properties, just defining the common methods get() and set() does not generate any special behavior, for example:

class Student(object):
    def __int(self, age=0):
        self._age = age
    
    # getter method
    def get(self):
        return self._age
    
    # setter method
    def set(self, value):
        self._age = value
        
xiaoming = Student()
# Use the setter method to set the age
xiaoming.set(20)
# Use getter method to return age
print(xiaoming.get())
print(xiaoming._age)

Output:

20
20

In the above code, set_age() and get_ The age () method is no different from ordinary methods, so how to implement the same functions as getter s and setter s? This requires a special method property() in python.
Use the property() method to implement the behavior of setter s and getter s
property() is a built-in method in python, which creates and returns a property object. A property object has three methods, getter(), setter(), and delete(). The property() built-in method has four parameters: property(fget,fset, fdel, doc). Fget is a function for obtaining attribute values, fset is a function for setting attribute values, fdel is a function for deleting attributes, and doc is used to create documentation for attributes. There are three methods to fulfill an attribute. getter(), setter() and delete() formulate fget, fset and fdel respectively.

class Adult(object):
    def __int(self):
        self.__age = 0
    
    # Get properties_ Value of age
    def get_age(self):
        print('getter() method called')
        return self.__age
    
    # Set properties_ Value of age
    def set_age(self, value):
        print('setter() method called')
        self.__age = value
    
    # Delete attribute_ age
    def del_age(self):
        del self.__age
        
    age = property(get_age, set_age, del_age)

laowang = Adult()
laowang.age = 60
print(laowang.age)

Output:

setter() method called
getter() method called
60

In the above code, age is a property object, which ensures secure access to private variables.
Use the @ property decorator to implement the behavior of setter s and getter s
In addition to using the method of property() above to implement the behavior of getter and setter methods, you can also implement the decorator @ property in python@ Property is a built-in decorator of python. The purpose of using the decorator is to change the methods or properties of the class, so that the caller does not need to make any changes in the code.

class Adult(object):    
    def __init__(self):
        self.__age = 0
    
    @property
    def age(self):
        print('getter() method called')
        return self.__age
        
    @age.setter
    def age(self, value):
        if value < 18:
            raise ValueError('Sorry, you are a child, games not allowed')
        print('setter() method called')
        self.__age = value
        
xiaoli = Adult()
xiaoli.age = 19
print(xiali.age)

Output:

setter() method called
getter() method called
19

The above code clearly shows how to use the @ property decorator to implement setter and getter properties in a python way. At the same time, the validity check of attribute assignment is realized.

Tags: Python

Posted by geo115fr on Sat, 14 May 2022 01:55:57 +0300