Python Note 5: decorator, built-in functions, json, and pythonjson

Source: Internet
Author: User
Tags decimal to binary

Python Note 5: decorator, built-in functions, json, and pythonjson
Decorator

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

Let's take a look at a simple example:

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

There is a new requirement. to record the running time of the function, you 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 other functions also have type requirements. How can this problem be solved? If you write a start time and end time in each function, and then calculate the difference value, the code is 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 cannot be understood, but in this way, each time a function is passed as a parameter to the timer () function, and this method has broken the original code logic structure, run () was run when the business logic was previously executed, but now timer () has to be run (). The above problems can be solved by using the decorator.

Simple decorator
Def timer (func): # Calculate the time def deco (* args, ** kwargs): # You can pass the parameter 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, which is the variable def run (): # Business Code time. sleep (1) print ('run .... ') run = timer (run) # run is equivalent to decorun () # run call is equivalent to deco ()

A function is a variable. in python, a function is a variable, and a function name is a variable. This function name stores the memory address of the function, which stores the function body in the memory, during the call, find the function body from the memory address in the function name and then run the function. The function name is followed by parentheses to call this function. If you only write this function name, print the memory address of this function.

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

Def timer (func): # Calculate the time def deco (* args, ** kwargs): # You can pass the parameter 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, which is the variable @ timer # When you use the @ form to append the decorator to the function, this method is called. timer (func) returns the function name deco, so run = deco, and the function name is the variable. At this time, the run code has been updated. func () = the code before run def run (): # Business Code time. sleep (1) print ('run .... ')
Run ()

The code after the run () function is updated is as follows: in fact, the run code has not been directly changed, but the run code is updated when the decorator 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, 11,-1]) # determine whether all values in the iteratable object are true. If one value is False, it is False, if it is not null, it is true. If it is not 0, it is true print (any ([0, 1, 2]). # determine whether the value in the iteratable object is true, trueprint (bin (10) # convert decimal to binary print (bool ('sdf ')) # convert an object to a boolean type func = ''print (callable (func) # determine whether the input object is callable. func is a variable and cannot be called. That is, Falsedef () is returned (): passprint (callable (adf) # determine whether the input object can be called by calling the method, that is, return Trueprint (chr (98) # print the ASCII code corresponding to the number, 98 = bprint (ord ('A') # print the ASCII code corresponding to the string, a = 97 print (dict (a = 1, B = 2) # convert it into a dictionary, {'B': 2, 'A': 1} # print (eval ('[a = 1]') print (exec ('def (): pass ') # execute python code. You can only execute simple statements. Define the data type and operation def func (num): name = '88' print (locals ()) print (globals () return numprint (list (filter (func, [0, 1, 2, 3, 4]) # In python3, filter (func, [1, 2, 3, 4]) # according to the processing logic of the previous function, process each element in the iteratable object in sequence, and return true to save print (list (map (func, [0, 1, 2, 3, 4]). # based on the previous function processing logic, process each element in the next iteratable object in sequence, and save all the results returned by the previous function </span> print (globals ()) # return all variables in the program. A dictionary is returned. The local variables in the function do not return print (locals () # Return the local variable print (hex (111 )) # convert a number to a hexadecimal print (max (111, 12, 13, 14, 16, 19) # obtain the maximum value print (oct (111 )) # convert a number to an octal print (round (11.1198, 2) # Take a few decimal places and round it to print (sorted ([2, 31, 34, 6, 1, 23, 4], reverse = False) # Sort
Dic = {,} print (sorted (dic. items () # sort by dictionary key, [(1, 2), (3, 4), (5, 6), (7, 8)] print (sorted (dic. items (), key = lambda x: x [1]) # Sort import time by dictionary value # import a module import sysprint (sys. path) # view the system environment variables in sys. path. append (r 'e: \ python_workspace \ base-Code') # Add the code under base-code to the environment variable, allowing python xxx. py does not report an error from day4.day5 _ test import hhhhhh () # Right-click and allow No error. If python model2.py is used, an error is returned. No module named 'day4' is found in day4 module'
Random Module
Import randomprint (random. randint (1, 20) # randomly generate an integer between 1 and 19, random print (random. choice ('abs123') # randomly fetch an element and iterate the objects: String, Dictionary, list, And tuple print (random. sample ('abcdefgrtw12', 3) # random element, 3 is the length, ['2', 'A', 'B'], the returned result is print (random. uniform (1, 9) # random floating point number, random floating point between 1-9, range can be specified, 5.8791750348305625 print (random. random () # random 0-1 floating point number, 0.9465901444615?random.shuffle ([1, 2, 3, 4, 5, 6]) # randomly disrupt the list Value, only list
JSON Functions

To use the JSON function, you need to import the json Library:Import json.

Function Description
Json. dumps Converts a dictionary to a json string.
Json. dump Write the json string converted from the dictionary into the file
Json. loads Converts a json string to a dictionary.
Json. load Reads json data from the file and converts it to a dictionary.

 

For example:

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) # from. when reading data in the json file, the returned results are: {'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) # convert the json string to the dictionary: {'age': 20, 'status': True, 'name': 'niuniu '}

Json. dump ()

Import jsonwith open ('a. json ', 'a +') as fp: dic = {'name': 'uniu', 'age': 18} fp. seek (0) fp. truncate () json. dump (dic, fp) # convert the dictionary into a json string and write it into a file

The written a. json is as follows:

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

Json. dumps ()

Import jsondic = {'name': 'uniu', 'age': 18} print (json. dumps (dic) # convert the dictionary into a json string: {"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.