Python learning: the use of Python @property decorator

Table of contents

1. Introduction of decorator @property

2. Example display

2.1. Create read-only properties

2.2. Modification methods, access methods like attributes


1. Introduction of decorator @property

Definition: The decorator @property is used to modify the method, which mainly has the following two functions:

  1. for creating read-only properties
  2. Decorate methods, access methods like properties

2. Example display

2.1. Create read-only properties

class Human(object):
    def __init__(self,value):
        self._age=value

    @property
    def age(self):
        return self._age


if __name__ == '__main__':
    peter=Human(18)
    print("the age of peter is {}".format(peter.age))
    #peter.age=20 #如果要修改属性将会报错

result:

 

AttributeError: can't set attribute will be raised if the attribute is set 

2.2. Modification methods, access methods like attributes

If we want to access the method like a property, instead of creating a read-only property, we can use it as follows

class Human(object):
    def __init__(self,value):
        self._age=value

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self,value):
        self._age=value



if __name__ == '__main__':
    peter=Human(18)
    print("the age of peter is {}".format(peter.age))
    peter.age=20 #修改属性不会报错
    print("the age of peter is {}".format(peter.age))

result:

 

Guess you like

Origin blog.csdn.net/qq_23345187/article/details/129160298