Python defines properties based on the property() function

Time:2020-3-23

This article mainly introduces Python’s definition of properties based on the property() function. The example code is introduced in detail in this article, which has a certain reference value for your study or work. You can refer to the following for your friends

Under normal circumstances, the properties contained in a class should be hidden, and only the methods provided by the class are allowed to indirectly access and operate the properties of the class.

class Person:
  #Constructor
  def __init__(self, name):
    self.name = name
  #Function to set the value of the name property
  def setname(self, name):
    self.name = name
  #Function to access the value of the name property
  def getname(self):
    return self.name
  #Function to delete name attribute value
  def delname(self):
    self.name = "xxx"
xiaobai = Person("xiaobai")
#Get name attribute value
print(xiaobai.getname())
#Set name property value
xiaobai.setname("xiaohei")
print(xiaobai.getname())
#Delete name attribute value
xiaobai.delname()
print(xiaobai.getname())

xiaobai
xiaohei
xxx

Python provides the property() function, which enables developers to use the “class object. Property” method to operate the properties in the class without breaking the class encapsulation principle.

class Person:
  #Constructor
  def __init__(self, name):
    Self. \u name = name \\
  #Function to set the value of the name property
  def setname(self, name):
    self.__name = name
  #Function to access the value of the name property
  def getname(self):
    return self.__name
  #Function to delete name attribute value
  def delname(self):
    self.__name = "xxx"
  #Configure the property () function for the name property
  Name = property (getname, setname, delname, 'description document')
#Two ways to call instruction documents
print(Person.name.__doc__)
help(Person.name)
xiaobai = Person("xiaobai")
#Get name attribute value
print(xiaobai.name)
#Set name property value
xiaobai.name = "xiaohei"
print(xiaobai.name)
#Delete name attribute value
del xiaobai.name
print(xiaobai.name)
Description document
Help on property:

  Description document

xiaobai
xiaohei
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.