SoFunction
Updated on 2024-11-18

Setting access to class properties via property in Python

All properties of Python classes are public and cannot be set to private, i.e., any instance object can have access to them by that property name. To achieve encapsulation performance similar to that of C++ classes, you can use properties to set access to Python class properties.

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

1 Define methods for accessing class attributes

The code is shown below

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

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

2 Setting up access to class properties using property()

After defining the methods for getting and setting the properties, the methods for accessing the class properties are set inside class A using property() as shown in the code below.

name = property(get_name, set_name)

Where the first parameter of property() indicates the method to be called to get the specified property and the second parameter indicates the method to be called to set the specified property.

3 Getting and Setting Specified Properties

Get and set the specified property with the following code.

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

The first print() prints a1.my_name, which actually calls the first parameter of property(), i.e., get_name() to get the attribute name of class A. After that, the attribute name of class A is set through a1.my_name, which calls the set_name() method of class A.

4 Property() Extended Usage

The meanings of the first two parameters of property() were mentioned in "2 Setting up methods for accessing class attributes with property()". the third parameter of property() indicates the method that is automatically called when an instance object is deleted (del), while the fourth parameter is of type string and indicates the description of the class. description that is displayed when the __doc__ property 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, 'I am class A')

After that, use the following code in the main program

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

At this point, the program prints the information "I am class A" and "del_name".

To this point this article on Python through the property set class property access to this article, more related Python property set class property content please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!