Setting access to class attributes through modifiers in Python

In "Setting access to class attributes through property in Python", it is mentioned that the method that is called by default when accessing class attributes can be set through property(). In addition to using property(), you can also use modifiers to achieve the above purposes.

1 Method of obtaining attributes through modifier settings

You can use the @property modifier to set the method that is called by default when getting properties. The code is as follows.

class A:
    def __init__(self, name):
        self.name = name
    @property
    def my_name(self):
        return self.name

Among them, the method my_name of class A is modified by @property. When the class attribute value is obtained, this method is called by default. The code is as follows.

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

At this time, the printed information is "yang".

2 Methods of setting specified attribute values ​​through modifiers

You can use the @XXX.setter modifier to set the method that is called by default when specifying the attribute value, where XXX has the same name as the specified method. Inside class A, add the following code.

@my_name.setter
    def my_name(self, name):
        self.name = name

At this time, the method my_name() of class A is modified by @my_name.setter. When the class attribute value is specified, this method is called by default. The code is as follows.

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

At this time, the printed information is "li".

It should be noted that the method names modified by @property and @XXX.setter must be the same.

Guess you like

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