Principle analysis of Python @ property decorator

Time:2020-3-24

This article mainly introduces the principle analysis of Python @ property decorator. The example code is introduced in detail in this article, which has certain reference value for your study or work. You can refer to the following for your friends

1. Through @ property decorator, you can access the method directly through the method name without adding a pair of “()” brackets after the method name.

class Person:
  def __init__(self, name):
    self.__name = name
  @property
  def say(self):
    return self.__name
xioabai = Person("xiaobai")
#Access the say method directly through the method name
Print ("my name is:", Xiaobai. Say)
My name is Xiaobai

In the above program, @ property is used to modify the say () method, which makes the method become the getter method of the name property.

2. Using setter decorator, you can add setter method to say method.

class Person:
  def __init__(self, name):
    self.__name = name
  @property
  def say(self):
    return self.__name
  @say.setter
  def say(self, value):
    self.__name = value
xiaobai = Person("xiaobai")
xiaobai.say = "xiaohei"
Print ("my name is actually:", Xiaobai. Say)
My name is: Xiaohei

3. Use the delete decorator to delete the specified attribute. You can add the delete method to the say method

class Person:
  def __init__(self, name):
    self.__name = name
  @property
  def say(self):
    return self.__name
  @say.setter
  def say(self, value):
    self.__name = value
  @say.deleter
  def say(self):
    self.__name = "xxx"
xiaobai = Person("xiaobai")
del xiaobai.say
Print ("my name is actually:", Xiaobai. Say)
My name is actually XXX

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.