Python programming ideas (26): member variables

Posted by toro04 on Sun, 28 Jun 2020 05:29:10 +0200

Miss Lining has launched the Python programming thought e-book in the WeChat official account of geek origin, which includes the core technology of Python and the usage of Python's main function library. Readers can enter 160442 in the official account of geek origin and begin learning.

General catalog of Python programming ideas

Python programming ideas column

 

catalog

1. Class variable and instance variable

2. Use property function to define property

The variables defined in the class body belong to the class itself by default. If a class is regarded as a class namespace, the class variable is actually a variable defined in the class namespace.

1. Class variable and instance variable

Variables defined in the class namespace belong to class variables. Python can use classes to read and modify class variables. For example, the following code defines a Teacher class and multiple class variables for it.

Example code: class_var.py

class Teacher :
    name = 'Li Ning'
    salary = 66666.66
    post_code = '12345678'
    def print_info (self):
        # Try to access class variables directly
#        print(name) # report errors
        # Accessing class variables through classes
        print(Teacher.name) # Export to Guangzhou
        print(Teacher.post_code) # Output 510660
# Class to access class variables of Address class
print(Teacher.name)
teacher = Teacher()
teacher.print_info()
# Modify the class variable of the Teacher class
Teacher.name = 'Wang Jun'
Teacher.post_code = '87654321'
teacher.print_info()

In this code, two class variables are defined for the Teacher class.

For class variables, they belong to the variables defined in the class namespace, so the program cannot directly access these variables, and the program must use the class name to call class variables. Whether accessing these class variables in the global scope or in the function, you must use the class name to access them.

When the program calls the print of the Teacher object for the first time_ When the info() method outputs two class variables, the initial values of these two class variables will be output. Next, the program modifies the values of two class variables through the Teacher class, so when the program passes print for the second time_ When the info method outputs two class variables, the modified values of these two class variables will be output.

Run the above code and you will see the following output:

Li Ning
 Li Ning
12345678
 Wang Jun
87654321

In fact, Python fully allows objects to be used to access class variables of the class to which the object belongs. Look at the following procedure:

Example code: class_instance_access_classvar.py

class Country:
    # Define two class variables
    value1 = 'China'
    value2 = 960
    def print_info (self):
        print('info In the method: ', self.value1)
        print('info In the method: ', self.value2)

country = Country()
print(country.value1) # China
print(country.value2) # 960
country.print_info()
    
# Modify two class variables of the Country class
Country.value1 = 'U.S.A'
Country.value2 = 1234
# Call print_info() method
country.print_info()

Two class variables are defined in the Country class of this code. Next, the program can use the Country object to access these two class variables.

The print of the Country class in this code_ In the info method, the program uses self to access the class variable of the Country class, where self represents print_ The caller of the info method, the Country object, so this is legal.

In the main program code area, the program creates the Country object and calls the value1 and value2 variables of the Country object through the object, which is also legal.

In fact, when a program accesses class variables through objects, its essence is to access class variables through class names. Run the above program, and you will see the following output:

China
960
 In info method: China
 In info method: 960
 In info method: US
 In info method: 1234

Because the nature of accessing class variables through objects is still accessed through class names, if class variables change, the modified values will be read when the program accesses these class variables. For example, add the following code to the program (followed by the previous code) and modify the two class variables of the Country class.

Country.value1='the republic of korea'
Country.value2 = 250
# Call info() method
country.print_info()

The above program modifies two class variables of the Country class, and then calls the print)info instance method through the object. Run the above code and you will see the following output.

In info method: Korea
 In info method: 250

From the above output, we can see that the essence of accessing class variables through instances is still accessing through class names. It should be noted that Python allows class variables to be accessed through objects, but if a program attempts to assign a value to a class variable through an object, the property changes. Python is a dynamic language, and assignment statements often mean defining new variables. Therefore, if a program assigns a value to a class variable through an object, it does not assign a value to a class variable, but defines a new instance variable.

Look at the following code:

Instance code: new_class_var.py

class Product:
    # Define two class variables
    name = 'iMac'
    price = 11000
    # Define instance methods
    def buy(self, name, price):
        # The following assignment statement does not assign a value to a class variable, but defines a new instance variable
        self.name = name
        self.price = price

# Create Product object
product = Product()
product.buy('iPhone', 8000)
# Access the name and price instance variables of product
print(product.name) # iPhone
print(product.price) # 8000
# Access the name and price class variables of Product
print(Product.name) # iMac
print(Product.price) # 11000

Product.name = 'Class variable name'
Product.price = 'Class variable price'
# Access the name and price instance variables of product
print(product.name)
print(product.price)

product.name = 'Instance variable name'
product.price = 'Instance variable price'
print(Product.name)
print(Product.price)

In this code, the assignment of name and price variables by instance looks like the assignment of class variables, but in fact, it does not, but redefines two instance variables (if the method is called for the first time).

After calling the buy() method of the Product object in this diamante, we access the name and price variables of the Product object. Since the object itself already has these two instance variables, the program will output the value of the object's instance variable. Next, the program accesses its name and price class variables through product, which is the real access to class variables.

Run the above program, and you will see the following output:

iPhone
8000
iMac
11000
iPhone
8000
 Class variable name
 Class variable price

If the program modifies the value of two class variables through the class, the value of the instance variable of Product in the program will not be affected. For example, the following code.

Product.name = 'Class variable name'
Product.price = 'Class variable price'
# Access the name and price instance variables of product
print(product.name)
print(product.price)

Run the above code, and you can see the following output results

iPhone
8000

The above program modifies the values of two class variables in the Product class at the beginning, but this modification has no effect on the instance variables of the Inventory object. Similarly, if the program modifies the instance variables of one object, such modification will not affect the instance variables of class variables and other objects. For example, the following code.

product.name = 'Instance variable name'
product.price = 'Instance variable price'
print(Product.name)
print(Product.price)

Run the above code and you will see the following output.

Class variable name
 Class variable price

From the above output results, the program output is still the two values previously assigned to class variables.

2. Use property function to define property

If accessor methods such as getter and setter are defined for Python classes, they can be defined as properties (equivalent to instance variables) using the property function.

The syntax format of the property function is as follows:

property(fget=None, fset=None, fdel-None, doc=None)

As can be seen from the above syntax format, when using the property function, four parameters can be passed in, representing getter method, setter method, del method and DOC respectively, where doc is a document string to describe the property. Of course, when developers call property, they can also pass in 0 (properties that cannot be read or written), 1 (read-only properties), 2 (read-write properties), 3 (read-write properties, or deleted) and 4 (read-write properties, or deleted, including document descriptions) parameters.

For example, the following program defines a Rectangle class that uses the property function to define a size property.

Example code: rectangle.py

class Rectangle:
    # Define construction method
    def __init__(self, width, height):
        self.width = width
        self.height = height
    # Define set_size() function
    def set_size (self , size):
        self.width, self.height = size
    # Define the getsize() function
    def get_size (self):
        return self.width, self.height
     # Define the getsize() function
    def del_size (self):
        self.width, self.height = 0, 0  
    # Defining properties using property
    size = property(get_size, set_size, del_size, 'Properties used to describe the size of the rectangle')
# Access the description document for the size property
print(Rectangle.size.__doc__)
# View through the built-in help() function Rectangle.size Description document for
help(Rectangle.size)
rect = Rectangle(5, 6)
# Access the size property of rect
print(rect.size) # (5, 6)
# Assign value to size attribute of rect
rect.size = 10, 12
# Access rect's width and height instance variables
print(rect.width) # 10
print(rect.height) # 12
# Delete size attribute of rect
del rect.size
# Access rect's width and height instance variables
print(rect.width) # 0
print(rect.height) # 0

This code uses the property function to define a size property. When defining the property, four parameters are passed in, which means that the property is readable, writable, deletable, and documented. Therefore, the program attempts to read, write and delete the size attribute of the Rectangle object. In fact, the read, write and delete operations are entrusted to get respectively_ size(), set_size() and del_size() method.

Run the above program, and you will see the following output results:

Properties used to describe the size of the rectangle
Help on property:

    Properties used to describe the size of the rectangle

(5, 6)
10
12
0
0

When you define properties using the property function, you can also pass in a small number of parameters as needed. For example, the following code uses the property function to define a read-write property that cannot be deleted.

class Person :
    def __init__ (self, first, last):
        self.first = first
        self.last = last
    def get_fullname(self):
        return self.first + ',' + self.last
    def set_fullname(self, fullname):
        first_last = fullname.rsplit(',');
        self.first = first_last[0]
        self.last = first_last[1]
    # Use the property() function to define the fullname property, passing in only 2 Parameters
    # This property is read-write, but cannot be deleted
    fullname = property(get_fullname, set_fullname)
p = Person('Zilong', 'Zhao')
# Access fullname property
print(p.fullname)
# Assign value to fullname property
p.fullname = 'Cloud growth,shut'
print(p.first)
print(p.last)

In this code, the fullname property is defined by using the property function. When using the property() function, the program only passes in two parameters as getter and setter methods, respectively. Therefore, the property is a read-write property and cannot be deleted.

Run this code and you will see the following output:

Zilong, Zhao
 Cloud growth
 shut

-----------------Support author please forward this article, or add teacher Li Ning's wechat: unitymarvel, or scan the following QR code and wechat--------

Welcome to WeChat's official account of the geeks, more exciting videos and articles waiting for you!

 

 

Topics: Python Programming Attribute