Home  >  Article  >  Backend Development  >  Detailed explanation of decorators, built-in functions, and json in python

Detailed explanation of decorators, built-in functions, and json in python

零下一度
零下一度Original
2017-06-25 10:24:271332browse

Decorator

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

Look at a simple example first:

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

There is a new requirement. I hope to record the running time of the function. The code that needs 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 other functions also have type requirements. How to do this? 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 specifically calculate the execution time, and then execute the real business code, as follows:

def timer(func):      #计算时间start_time = time.time()
    func()
    end_time = time.time()print('run time', end_time - start_time)    
def run():           #业务代码time.sleep(1)print('run....')
timer(run)

The logic of the above code cannot be understood, but in this case, a function is passed as a parameter to the timer() function every time, and this method has destroyed the original code logical structure. Before execution When the business logic is executed, run() is run, but now it has to run timer(). Using decorators, you can solve the above problems.

Simple Decorator

def timer(func):      #计算时间def deco(*args, **kwargs):   #可以传参start_time = time.time()
        func(*args, **kwargs)    #函数调用end_time = time.time()print('run time', end_time - start_time)return deco               #return 函数名,函数即变量def run():           #业务代码time.sleep(1)print('run....')

run = timer(run)       #run相当于decorun()                  #run调用相当于deco()

Function is a variable. A function in python is a variable, and the function name is a variable. This function name stores the function's Memory address, it puts the function body into the memory. When calling, find the function body from the memory address in the function name and then run the function. Adding parentheses after the function name means calling the function. If you only write the function name, print the memory address of the function.

The function timer is a decorator. It wraps the func that executes the real business method in the function. It looks like the run is decorated by the timer. The evolution continues as follows:

 timer(func):       deco(*args, **kwargs):   start_time =*args, **kwargs)    end_time =(, end_time - deco               @timer                run():           time.sleep(1()
run()

The updated code of the run() function is as follows: In fact, the run code has not been directly changed, but when the decorator is called, the run code 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]))   #判断可迭代对象里面的值是否都为真,有一个为假即为False,非空即真非0即真print(any([0, 1, 2]))              #判断可迭代对象里面的值是否有一个为真,即为Trueprint(bin(10))                    #将十进制转换为二进制print(bool('sdf'))                   #将一个对象转换为布尔类型func = ''print(callable(func))             #判断传入的对象是否可调用,func为变量不可调用,即返回Falsedef adf():passprint(callable(adf))             #判断传入的对象是否可调用,adf为方法即可调用,即返回Trueprint(chr(98))               #打印数字对应的ASCII码,98=bprint(ord('a'))              #打印字符串对应的ASCII码, a=97print(dict(a=1, b=2))        #转换成字典,{'b': 2, 'a': 1}#print(eval('[a=1]'))print(exec('def a():pass'))   #执行python代码,只能执行简单的,定义数据类型和运算def func(num):
    name = '88'print(locals())print(globals())return numprint(list(filter(func, [0, 1, 2, 3, 4])))  #在python3里面这么用是没问题filter(func, [1, 2, 3, 4])                  #根据前面的函数处理逻辑,依次处理后面可迭代对象里面的每个元素,返回true保存print(list(map(func, [0, 1, 2, 3, 4])))      #根据前面的函数处理逻辑,依次处理后面可迭代对象里面的每个元素,保存前面函数返回的所有结果 </span>print(globals())                             #返回程序内所有的变量,返回的是一个字典,函数里面的局部变量不会返回print(locals())                              #返回局部变量print(hex(111))                              #数字转成16进制print(max(111, 12, 13, 14, 16, 19))           #取最大值print(oct(111))                              #把数字转换成8进制print(round(11.1198, 2))                      #取几位小数,会四舍五入print(sorted([2, 31, 34, 6, 1, 23, 4], reverse=False))#排序
dic={1:2,3:4,5:6,7:8}print(sorted(dic.items()))                         #按照字典的key排序,[(1, 2), (3, 4), (5, 6), (7, 8)]print(sorted(dic.items(), key=lambda x:x[1]))     #按照字典的value排序import time                          #导入一个模块import sysprint(sys.path)   #查看系统环境变量有哪些目录sys.path.append(r'E:\python_workspace\base-code')  #将base-code下的代码添加到环境变量,允许python xxx.py就不报错from day4.day5_test import hhh
hhh()                                            #直接右键允许不报错,使用python  model2.py允许时报错,找不到day4模块No module named 'day4'

random module

import randomprint(random.randint(1, 20))             #在1-19之间随机生成一个整数,随机print(random.choice('abs123'))           #随机取一个元素,随机可迭代对象:字符串、字典、list、元组print(random.sample('abcdfgrtw12', 3))   #随机取几个元素,3是长度,['2', 'a', 'b'],返回结果是list类型print(random.uniform(1, 9))              #随机浮点数,随机取1-9之间的浮点数,可指定范围,5.8791750348305625print(random.random())                    #随机0-1的浮点数,0.9465901444615425random.shuffle([1, 2, 3, 4, 5, 6])  #随机打乱list的值,只能是list

JSON function

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

Function Description
json.dumps Convert dictionary to json string
json.dump Write the dictionary-converted json string to the file
json.loads Convert json string to dictionary
json.load Read json data from the file and then convert it to dictionary

For example, 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)  #从a.json文件内读取数据,返回结果为字典:{'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))         #将json串转换为字典:{'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)    #将字典转换为json串写入文件

The a.json written is as follows:

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

json.dumps( )

import json
dic = {'name': 'niuniu', 'age': 18}print(json.dumps(dic))           #将字典转换为json串:{"name": "niuniu", "age"

The above is the detailed content of Detailed explanation of decorators, built-in functions, and json in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn