current position:Home>Django -- closure decorator regular expression

Django -- closure decorator regular expression

2022-02-01 10:59:53 RIP_ Mamba

「 This is my participation 11 The fourth of the yuegengwen challenge 25 God , Check out the activity details :2021 One last more challenge 」.

1.property attribute

Concept :property An attribute is responsible for using a method as an attribute , This can simplify the use of code .

Definition property Properties have two ways :

  • Decorator mode ;
  • Class attribute mode .

1.1 Decorator mode

class Person(object):

    def __init__(self):
        self.__age = 0

    #  Decorator mode property, hold age Method as an attribute , Indicates that the following decorated method will be executed when obtaining the attribute 
 @property
    def age(self):
        return self.__age

    #  hold age Method as an attribute , Indicates that the following decorated methods will be executed when setting properties 
 @age.setter
    def age(self, new_age):
        if new_age >= 150:
            print(" It's refined ")
        else:
            self.__age = new_age

p = Person()
print(p.age)
p.age = 100
print(p.age)
p.age = 1000
 Copy code 

explain :

  • @property: Indicates that the method is used as an attribute , Indicates that the following decorated method will be executed when obtaining the attribute ;
  • @ Method name .setter: Indicates that the method is used as an attribute , Indicates that the following decorated methods will be executed when setting properties ;
  • Decorator mode property The method name of attribute modification must be the same .

1.2 Class attribute mode

class Person(object):
    def __init__(self):
        self.__age = 0

    def get_age(self):
        """ When getting age The method will be executed when the property """
        return self.__age

    def set_age(self, new_age):
        """ When setting age The method will be executed when the property """
        if new_age >= 150:
            print(" It's refined ")
        else:
            self.__age = new_age

    #  Class attribute mode property attribute 
    age = property(get_age, set_age)

p = Person()
print(p.age)
p.age = 100
print(p.age)
p.age = 1000
 Copy code 

property Parameter description of :

  • The first parameter is the method to execute when getting the property ;
  • The second parameter is the method to be executed when setting the property .

2.with Statement and context manager

with open("xxx.txt", "w") as f:
    f.write("hello python")
 Copy code 

Writing in this way will automatically close the file after execution , Avoid mistakes .

2.1 Context manager

As long as a class implements __enter__() and __exit__() These two methods , The objects created through this class are called context managers .

The context manager can use with sentence ,with Behind the statement is the context manager :

class File(object):

    #  Initialization method 
    def __init__(self, file_name, file_model):
        #  Define variable save file name and open mode 
        self.file_name = file_name
        self.file_model = file_model

    #  Context method 
    def __enter__(self):
        print(" Go to the above method ")
        self.file = open(self.file_name, self.file_model)
        return self.file

    #  The following method 
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(" Go to the following method ")
        self.file.close()

if __name__ == '__main__':
    with File("1.txt", "r") as file:
        file_data = file.read()
        print(file_data)
 Copy code 

explain :

  • __enter__() Represents the context method , You need to return an operation object ;
  • __exit__() Means the following method ,with When the statement is completed, it will be executed automatically , This method is executed even if an exception occurs .

2.2 Another implementation of context manager

If you want a function to be called a context manager ,Python One is also provided @contextmanager The decorator , It further simplifies the way the context manager is implemented .

adopt yield Split the function into two parts ,yield The above sentence is __enter__() Method execution ,yield The following statement is in __exit__() Method execution , Keep up with the yield The following parameters are the return value of the function :

#  Lead in the decorator from contextlib import contextmanager

#  Decorator decorator function , Call it a context manager object 
@contextmanagerdef my_open(path, mode):
    try:
        #  Open file 
        file = open(file_name, file_mode)
        # yield The previous code is like the above method 
        yield file
    except Exception as e:
        print(e)
    finally:
        print("over")
        # yield The following code is like the following method 
        file.close()

#  Use with sentence with my_open('out.txt', 'w') as f:
    f.write("hello , the simplest context manager")
 Copy code 

3. How the generator is created

Concept : Generate data circularly according to the rules set by the programmer , When the condition does not hold, the generated data ends . Generate... Not all data at once , Instead, use a , Regenerate into one , Sure Save a lot of memory .

How to create a generator :

  • Generator derivation ;
  • yield keyword .

3.1 Generator derivation

Similar to the list derivation , It's just that the generator derivation uses parentheses :

""" Generator derivation """
my_generator = (i*2 for i in range(5))
print(my_generator)

for value in my_generator:
    print(value)

# next Get the next value of the generator 
# value = next(my_generator)
# print(value)
 Copy code 

next Function to get the next value in the generator .

3.2 yield keyword

As long as def Function yield keyword , So it's the generator :

def my_generator(n):
    for i in range(n):
        print(' To start generating ')
        yield i
        print(' Finish once ')

if __name__ == '__main__':
    g = my_generator(2)
    for i in g:
        print(i)
 Copy code 

Code instructions :

  • Code execution to yield Will suspend , Then return the result , Next time, the initiator will continue to execute at the suspended position ;
  • If the generator completes the data generation , Getting the next data in the generator again will throw a StopIteration abnormal , Indicates an exception to stop iteration ;
  • while There is no exception handling inside the loop , You need to manually add exception handling operations ;
  • for The stop iteration exception is automatically handled inside the loop , Recommended .

4. Deep copy and light copy

Shallow copy :copy The function is a shallow copy , Copy only the first level objects of variable types , Open up new memory space for the copied object for storage , Does not copy child objects inside objects .

  • Shallow copying of immutable types does not open up new memory space for the copied objects , It just copies the reference to the object ;
  • Shallow copy of variable types only copies the first layer objects of variable types , The copied objects will open up new memory space for storage , Child objects are not copied .

Deep copy :deepcopy The function is a deep copy , As long as an object is found to have a variable type, it will copy the object to each layer of the last variable type , For each layer of copied objects, new memory space will be opened up for storage .

  • Deep copy of immutable types , If the child object has no mutable type, it will not be copied , It just copies the reference to the object , Otherwise, the object will be copied to each layer of the last mutable type , For each layer of copied objects, new memory space will be opened up for storage .

5. Regular expressions

The practical application : Matches strings that meet some complex rules

Concept : Regular expressions are codes that record text rules (0\d{2}-\d{8} This is a regular expression , It means matching the number of the line )

5.1 re modular

stay python When you need to match strings through regular expression matching in , Import required re modular :

#  Import re modular import re

#  Use match Method to match 
result = re.match( Regular expressions , String to match )

#  If the previous step matches the data , have access to group Method to extract data 
result.group()
 Copy code 

re Use of modules :

import re

#  Use match Method to match 
result = re.match("itcast","itcast.cn")
#  Get matching results 
info = result.group()
print(info)
 Copy code 
  • re.match() Match string data from scratch based on regular expressions ;
  • re.search() Start from the beginning ;
  • re.findall() Find all ;
  • Not greed .

5.2 Match a single character

Code function
. Matches any character ( except \n)(re.S,re.DOTALL)
[] [] matching [] The characters listed in
\d Match the Numbers , namely 0-9
\D Match non numeric , It's not numbers
\s Match blanks , Such as space ,tab key
\S Match non blank
\w Match non special characters , namely a-z,A_Z,_, Chinese characters
\W Match special character , Non alphabetic 、 The digital 、 Non Chinese characters

5.3 Match multiple characters

Code function
* Match previous character appears 0 Times or countless times , You can have it or not
+ Match previous character appears 1 Times or infinite times , At least 1 Time
Match the previous character or appear 1 I don't want to show up 0 Time , You can have it or not
{m} Match previous character appears m Time
{m, n} Match previous character appears from m To n Time

5.4 Match the beginning and the end

Code function
^ Match the beginning of a string
$ Match string end
[^ Specify the characters ] Indicates that all characters except the specified ones match

5.5 Match groups

Code function
| Match any expression left or right
(ab) Use the characters in brackets as a group
\num Reference group num Matching string
(?P) Group aliases
(?P=name) Quote alias as name Group matched strings

copyright notice
author[RIP_ Mamba],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011059504209.html

Random recommended