property attribute

The definition and invocation of property attributes should pay attention to the following points:

  • When defining, add the @property decorator on the basis of the instance method; and there is only one self parameter

  • When calling, no parentheses are required

  • Method: foo_obj.func()

  • property property: foo_obj.prop

  • The function of Python's property attribute is: a series of logical calculations are performed inside the property attribute, and the calculation result is finally returned.

Two methods of property attribute

  • 3.1 Decorator methods

  • There is only one way to access a property in a classic class, which corresponds to a method decorated with @property

  • There are three access methods for the properties in the new class, and they correspond to the three access methods by @property, @method_name.setter, @method_name.deleter

  • 3.2 Class attribute method

  • Create a class property whose value is a property object

There are four parameters in the property method
  • The first parameter is the method name, which is automatically triggered to execute the method when the object.property is called
  • The second parameter is the method name, the calling object. When the attribute = XXX, the execution method is automatically triggered
  • The third parameter is the method name, and the execution method is automatically triggered when the del object is called.
  • The fourth parameter is a string, calling object.property.doc , this parameter is the description of the property
class Foo(object):
    def get_bar(self):
        print("getter...")
        return 'laowang'

    def set_bar(self, value): 
        """必须两个参数"""
        print("setter...")
        return 'set value' + value

    def del_bar(self):
        print("deleter...")
        return 'laowang'

    BAR = property(get_bar, set_bar, del_bar, "description...")

obj = Foo()

obj.BAR  # 自动调用第一个参数中定义的方法:get_bar
obj.BAR = "alex"  # 自动调用第二个参数中定义的方法:set_bar方法,并将“alex”当作参数传入
desc = Foo.BAR.__doc__  # 自动获取第四个参数中设置的值:description...
print(desc)
del obj.BAR

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325402744&siteId=291194637