Python Learn 06.10:Python property() Function: Define Variables

Keywords: Attribute Python

In the previous chapters, we have been accessing variables defined in classes in the form of class objects. variables, which is inappropriate because it violates the principle of class encapsulation.Normally, a class contains variables that should be hidden, allowing only indirect access to and manipulation of class variables through methods provided by the class.

Therefore, in order to effectively manipulate attributes in a class without breaking the principle of class encapsulation, the class should contain multiple getter (or setter) methods for reading (or writing) class attributes, so that variables can be manipulated by means of "class object.function (parameter)", for example:

class CLanguage:
    # Constructor
    def __init__(self,name):
        self.name = name 

    # Functions that set the name property value 
    def setname(self,name):
        self.name = name
    # Functions accessing nema property values
    def getname(self):
        return self.name

    # Functions that delete the value of the name attribute
    def delname(self):
        self.name="xxx"


clang = CLanguage("C Chinese Language Web")

# Get the name property value
print(clang.getname())

# Set name property value
clang.setname("Python Course")
print(clang.getname())

# Delete name attribute value
clang.delname()
print(clang.getname())


#The results are as follows:


C Chinese Language Web
Python Course
xxx

Readers may find this way of manipulating class variables more cumbersome and more accustomed to using class objects.variables.


Fortunately, the property() function is provided in Python to allow developers to manipulate variables in classes in a way that does not destroy the principle of class encapsulation.

The basic format for using the property() function is as follows:

Variable name= property(fget=None, fset=None, fdel=None, doc=None)

The fget parameter specifies the class method to get the value of the variable, the fset parameter specifies the method to set the value of the variable, the fdel parameter specifies the method to delete the value of the variable, and the doc is a document string that illustrates the function.

Note that when using the property () function, these four parameters can only be specified for the first, or the first two, or the first three, or they can all be specified now.That is, the assignment of parameters in the property() function is not entirely arbitrary.

For example, modify the program above to configure the property() function for the name property:

class CLanguage:
    # Constructor
    def __init__(self,n):
        self.__name = n

    # Functions that set the name property value
    def setname(self,n):
        self.__name = n

    # Functions accessing nema property values
    def getname(self):
        return self.__name

    # Functions that delete the value of the name attribute
    def delname(self):
        self.__name="xxx"

    # Configure the property() function for the name property
    name = property(getname, setname, delname, 'Indicate Origin')


# Two ways to fetch documentation
# print(CLanguage.name.__doc__)
help(CLanguage.name)
clang = CLanguage("C Chinese Language Web")

# Call the getname() method
print(clang.name)

# Call setname() method
clang.name="Python Course"
print(clang.name)

# Call the delname() method
del clang.name
print(clang.name)


# The result is


Help on property:

    //Indicate Origin

C Chinese Language Web
Python Course
xxx

Note that in this program, because the name variable needs to be returned in the getname() method, if self.name is used, it will itself be called getname(), which will lead to an infinite loop.To avoid this, the name variable in the program must be set to a private variable, using u name (the first two underscores).

Variable settings (public, protected, private) for class variables and class functions are described in more detail in subsequent chapters.

Of course, the property() function can also pass in a few fewer parameters.Using the above program as an example, we can modify the property() function as follows

name = property(getname, setname)

This means that name is a readable and writable variable, but it cannot be deleted because there is no method configured for name in the property() function to function that variable.That is, even if a delname() function is designed in the CLanguage class, it cannot be used to delete the name variable in this case.(

Similarly, you can use the property() function as follows:

name = property(getname) # The name attribute is readable, not writable, and cannot be deleted
name = property(getname, setname,delname) #The name attribute can be read, written, or deleted without a description document

Posted by listenmirndt on Wed, 19 Feb 2020 09:30:51 -0800