Access to class attributes through property settings in Python

All properties of a Python class are public and cannot be made private, i.e. any instance object can access it through the property name. In order to achieve encapsulation performance similar to C++ classes, you can use property to set the access permissions of Python class attributes.

The encapsulation performance of a class means that the attributes of the class can only be accessed through specified methods. Therefore, first define methods for the class to access the properties.

1 Define methods to access class attributes

The code is as follows

class A:
    def __init__(self, name):
        self.name = name
    def get_name(self):
        return self.name
    def set_name(self, name):
        self.name = name

Among them, class A has an attribute named name, which is obtained through the get_name() method and set through the set_name() method.

2 Use property() to set the method of accessing class attributes

After defining the methods for getting and setting attributes, use property() inside class A to set the method for accessing class attributes. The code is as follows.

name = property(get_name, set_name)

Among them, the first parameter of property() indicates the method to be called when obtaining the specified property, and the second parameter indicates the method to be called when setting the specified property.

3 Get and set specified attributes

Get and set the specified properties through the following code.

a1 = A('yang')
print(a1.my_name)
a1.my_name = 'li'
print(a1.my_name)

What is printed in the first print() is a1.my_name. At this time, the first parameter of property() is actually called, that is, get_name() gets the property name of class A; then it sets the property name of class A through a1.my_name. Attribute name, the set_name() method of class A is called at this time.

4 property() extended usage

The meaning of the first two parameters of property() is mentioned in "2 Using property() to set the method of accessing class attributes". The third parameter of property() represents the method that is automatically called when deleting (del) the instance object, and the type of the fourth parameter is a string, indicating a description of the class, which is displayed when the __doc__ attribute is displayed.

Add the following code inside class A:

def del_name(self):
        print('del_name')
my_name = property(get_name, set_name, del_name, '我是类A')

After that, use the following code in the main program

print(A.my_name.__doc__)
del a1.my_name

At this time, the program will print "I am class A" and "del_name" information.

Guess you like

Origin blog.csdn.net/hou09tian/article/details/132687597