python Notes 5: Decorators, Built-in Functions, json

Posted by maniac1aw on Fri, 21 Jun 2019 20:25:32 +0200

Decorator

The decorator is essentially a Python function, which allows other functions to add additional functions without any code changes. The return value of the decorator is also a function object.

Let's start with a simple example:

def run():
    time.sleep(1)
    print('run....')

There is a new requirement that we can record the running time of the function. We need to calculate the time in the code.

def run():
    start_time = time.time()
    time.sleep(1)
    print('run....')
    end_time = time.time()
    print('run time', end_time - start_time)

login() and many other functions also have different types of requirements. What should we do? If you write a start and end time in each function, and then calculate the difference, the code will be redundant. You can define a function to calculate the execution time, and then execute the real business code, as follows:

def timer(func):      #computing time
    start_time = time.time()
    func()
    end_time = time.time()
    print('run time', end_time - start_time)
    
def run():           #Business code
    time.sleep(1)
    print('run....')
timer(run)

The above code logic is incomprehensible, but in this case, each time a function is passed as a parameter to the timer() function, and this way has destroyed the original code logic structure. Before the execution of business logic, run() was executed, but now timer() has to be run. The above problems can be solved by using decorators.

Simple Decorator

def timer(func):      #computing time
    def deco(*args, **kwargs):   #It can be transmitted for reference.
        start_time = time.time()
        func(*args, **kwargs)    #function call
        end_time = time.time()
        print('run time', end_time - start_time)
    return deco               #return Function name, function is variable

def run():           #Business code
    time.sleep(1)
    print('run....')

run = timer(run)       #run Amount to deco
run()                  #run Call equivalent deco()

Function is a variable. The function in python is a variable and the function name is a variable. The function name stores the memory address of the function. It puts the function body in memory. When calling, it finds the function body from the memory address in the function name and runs the function. This function is called by adding parentheses after the function name. If you only write the function name, print out the memory address of the function.

Function timer is a decorator that wraps FuncS that perform real business methods in func tions and looks like run is decorated by timer. It continues to evolve as follows:

def timer(func):      #computing time
    def deco(*args, **kwargs):   #It can be transmitted for reference.
        start_time = time.time()
        func(*args, **kwargs)    #function call
        end_time = time.time()
        print('run time', end_time - start_time)
    return deco               #return Function name, function is variable
@timer               #Use @ This method is called when the form attaches the decorator to the function.timer(func) Returns the function name. deco,therefore run== deco,Function name is variable,here run Code updated,func() = run Previous code
def run():           #Business code
    time.sleep(1)
    print('run....')
run()

The code after the run() function update is as follows: in fact, the code of run has not been changed directly, but when the decorator is called, the code of run is updated.

def run():
    start_time = time.time()
    time.sleep(1)
    print('run....')
    end_time = time.time()
    print('run time', end_time - start_time)

python built-in function

print(all([1, 2, 3, 0, 11, -1]))   #Judging whether all the values in an iterative object are true or not, one is false. False,Non-empty is true, non-zero is true.
print(any([0, 1, 2]))              #To determine whether a value in an iterative object is true, that is True
print(bin(10))                    #Converting decimal to binary
print(bool('sdf'))                   #Converting an object to a Boolean type
func = ''
print(callable(func))             #Determine whether the incoming object is callable, func Not callable for variables, that is, returned False
def adf():
    pass
print(callable(adf))             #Determine whether the incoming object is callable, adf Callable as a method, that is, returned True
print(chr(98))               #Printed numerically corresponding ASCII Code, 98=b
print(ord('a'))              #Print String Corresponding ASCII Code, a=97
print(dict(a=1, b=2))        #Converting to a dictionary,{'b': 2, 'a': 1}
#print(eval('[a=1]'))
print(exec('def a():pass'))   #implement python Code, which can only perform simple, defined data types and operations
def func(num):
    name = '88'
    print(locals())
    print(globals())
    return num
print(list(filter(func, [0, 1, 2, 3, 4])))  #stay python3 It's okay to use it like this.
filter(func, [1, 2, 3, 4])                  #According to the previous function processing logic, each element in the following iteratable object is processed in turn and returned. true Preservation
print(list(map(func, [0, 1, 2, 3, 4])))      #According to the previous function processing logic, each element in the following iteratable object is processed in turn, and all the results returned by the previous function are saved. </span>
print(globals())                             #Returns all variables in the program, returning a dictionary,Local variables in functions do not return
print(locals())                              #Return local variables
print(hex(111))                              #Conversion of digits to hexadecimal
print(max(111, 12, 13, 14, 16, 19))           #Maximum
print(oct(111))                              #Converting digits to octal
print(round(11.1198, 2))                      #Take a few decimal places.,Round off
print(sorted([2, 31, 34, 6, 1, 23, 4], reverse=False))#sort
dic={1:2,3:4,5:6,7:8}
print(sorted(dic.items()))                         #According to the dictionary key sort,[(1, 2), (3, 4), (5, 6), (7, 8)]
print(sorted(dic.items(), key=lambda x:x[1]))     #According to the dictionary value sort
import time                          #Import a module
import sys
print(sys.path)   #See what directories the system environment variables have
sys.path.append(r'E:\python_workspace\base-code')  #take base-code The following code is added to the environment variable, allowing python xxx.py Don't make a mistake
from day4.day5_test import hhh
hhh()                                            #Direct right-click allows no error reporting, using python  model2.py Allow Times to Error, Not Found day4 Modular No module named 'day4'

random module

import random
print(random.randint(1, 20))             #At 1-19 Random generation of an integer, random
print(random.choice('abs123'))           #Random selection of an element, random iterative objects: string, dictionary, etc. list,tuple
print(random.sample('abcdfgrtw12', 3))   #Randomly take a few elements, 3 is the length.['2', 'a', 'b'],The return result is list type
print(random.uniform(1, 9))              #Random Floating Points, Random 1-9 Floating point number between, can specify range, 5.8791750348305625
print(random.random())                    #Random 0-1 The floating point number of 0..9465901444615425
random.shuffle([1, 2, 3, 4, 5, 6])  #Random disruption list The value of 0, can only be __________. list

JSON function

Using JSON functions requires importing the JSON library: import json.

function describe
json.dumps Converting a dictionary to a json string
json.dump Write the json string converted by the dictionary to the file
json.loads Converting json strings to dictionaries
json.load Read json data from a file and convert it to a dictionary

 

 

 

 

 

Examples are as follows:

a.json content format:

{"car":{"price":1100,"color":"red"},"mac":{"price":7999,"color":"black"},"abc":{"price":122,"color":"green"}}

json.load()

import json
with open('a.json') as fp:
    shop_dic = json.load(fp)  #from a.json Read the data in the file and return the result as a dictionary:{'abc': {'price': 122, 'color': 'green'}, 'mac': {'price': 7999, 'color': 'black'}, 'car': {'price': 1100, 'color': 'red'}}
    print(shop_dic)

json.loads()

s_json = '{"name":"niuniu","age":20,"status":true}'
print(json.loads(s_json))         #take json String to dictionary:{'age': 20, 'status': True, 'name': 'niuniu'}

json.dump()

import json
with open('a.json', 'a+') as fp:
    dic = {'name': 'niuniu', 'age': 18}
    fp.seek(0)
    fp.truncate()
    json.dump(dic, fp)    #Converting a dictionary to json String write file

Write a.json as follows:

{"age": 18, "name": "niuniu"}

json.dumps()

import json
dic = {'name': 'niuniu', 'age': 18}
print(json.dumps(dic))           #Converting a dictionary to json String:{"name": "niuniu", "age"

Topics: Python JSON ascii Mac