A detailed description of adorners, built-in functions, and JSON in Python

Source: Internet
Author: User

Decorative Device

An adorner is essentially a Python function that allows other functions to add extra functionality without any code changes, and the return value of the adorner is also a function object.

Let's look at a simple example:

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

There is a new requirement that you want 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)

Multiple functions, such as login (), also have types of requirements, what do you do? If you write a start and end time in each function and then calculate the difference, then the code is redundant, you can define a function that calculates the execution time, and then executes 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 above code logic does not understand, but in this case, each time a function is passed as a parameter to the timer () function, and this way has broken the original code logic structure, before the execution of business logic, run ran (), but now have to run the timer (). Using adorners, 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 function name, function is variable def run ():           #业务代码time. Sleep (1) print (' Run ... ') Run = timer (run)       #run相当于decorun ()                  #run调用相当于deco ()

function is a variable, the function in Python is a variable, the function name is a variable, the function name is stored in the memory address of the function, it put the function body in memory, at the time of the call from the memory address in the name of the function to find the functional body and then run the function. The function name is appended with parentheses to call this function, if you write only the function name, print it is the memory address of this function.

The function timer is the adorner, which wraps the func that executes the real business method inside the function, and looks like run was decorated with a timer. Continue to evolve as follows:

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

The run () function updates the code as follows: In fact, the code of the run does not change directly, but the code of Run is updated when the adorner is called.

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 functions

Print (All ([1, 2, 3, 0, one,-1])) #判断可迭代对象里面的值是否都为真, there is a false that is, non-null is true not 0 that is true print (any ([0, 1, 2])) #判断可迭代对象里面的值是 No one is true, that is, trueprint (BIN) #将十进制转换为二进制print (bool (' SDF ')) #将一个对象转换为布尔类型func = ' Print (Callable (func)) #判断传入的对象是否可调用, Func is a variable that is not callable, which returns FALSEDEF ADF ():p Assprint (callable (ADF)) #判断传入的对象是否可调 , the ADF is invoked as a method, which returns Trueprint (Chr (98)) #打印数字对应的ASCII码, 98=bprint (Ord (' A ')) #打印字符串对应的ASCII码, A=97prin T (Dict (A=1, b=2)) #转换成字典, {' B ': 2, ' A ': 1} #print (eval (' [a=1] ')) print (EXEC (' Def a ():p ') ') #执行python代码, can only perform simple, defined number According to type and Operation def func (num): name = ' locals ' Print (Globals ()) ' Return Numprint (List (func, [0, 1, 2, 3, 4])) #在 It's no problem in Python3. Filter (func, [1, 2, 3, 4]) #根据前面的函数处理逻辑, and then process each element in the subsequent iteration of the object, returning True to save print (list (the map (func, [                             0, 1, 2, 3, 4]))) #根据前面的函数处理逻辑, sequentially processing each element in the subsequent iteration of the object, saving all results returned by the previous function </span>print (Globals ()) #返回程序内所有的变量, the return is a wordCode, the local variables inside the function do not return print (locals ()) #返回局部变量print (Hex (111)) #数字转成16进制p Rint (Max (111, 11.11,,)) #取最大值print (Oct (111)) #把数字转换成8进制print (round (+ 98, 2)) #取几位小数, will be rounded to print (sorted ([2, 1, 6, 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)   # See what directory Sys.path.append (R ' E:\python_workspace\base-code ') #将base the system environment variable  to add the code under-code to the environment variable, allowing Python xxx.py no error from day4.day5_test import hhhhhh ()                                            #直接右键允许不报错, using Python  model2.py allow times to be wrong, unable to find Day4 module no module named ' Day4 '

Random module

Import Randomprint (Random.randint (1))             randomly generates an integer between #在1-19, Random print (Random.choice (' abs123 '))           #随机取一个元素, Randomly iterated objects: string, dictionary, list, tuple print (random.sample (' Abcdfgrtw12 ', 3))   #随机取几个元素, 3 is length, [' 2 ', ' A ', ' B '], return result is List type print ( Random.uniform (1, 9))              #随机浮点数, randomly take a floating-point number between 1-9, can specify the range, 5.8791750348305625print (Random.random ())                    #随机0-1 floating-point number, 0.9465901444615425random.shuffle ([1, 2, 3, 4, 5, 6])  #随机打乱list的值, can only be list

JSON functions

Use JSON functions to import the JSON library: importJSON.

Function Describe
Json.dumps Convert a dictionary to a JSON string
Json.dump Writes a dictionary-converted JSON string to a file
Json.loads Convert a JSON string to a dictionary
Json.load Read JSON data from a file and convert to a dictionary

For example, the following:

A.json content Format:

{"Car": {"Price": 1100, "color": "Red"}, "Mac": {' price ': 7999, "color": "Black"}, "abc": {"Price": 122, "color": "Green"}}

Json.load ()

Import Jsonwith Open (' A.json ') as fp:    shop_dic = json.load (fp)  #从a. json file to read the data 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 ': ' Status ': true} ' Print (Json.loads (S_json))         #将json串转换为字典: {' age ': ' Status ' : True, ' name ': ' Niuniu '}

Json.dump ()

Import Jsonwith Open (' A.json ', ' A + ') as fp:    dic = {' name ': ' Niuniu ', ' age ': $    fp.seek (0)    fp.truncate ()    Json.dump (DIC, FP)    #将字典转换为json串写入文件

The A.json are written as follows:

{"Age": +, "name": "Niuniu"}

Json.dumps ()

Import jsondic = {' name ': ' Niuniu ', ' Age ': 18}print (Json.dumps (DIC))           #将字典转换为json串: {"name": "Niuniu", "Age"
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.