Python--function (ii), adorner,

Source: Internet
Author: User
Tags shuffle

1. function is variable

function is a variable, hello is a variable, the output is a memory address, it stores the function body in memory; Hello () is a function, function name + parenthesis is called Function.

1  def Hello (): 2      Print ('nihao') 3  Print (hello) 4  Hello ()

2. Higher-order functions

When a Function's entry is a function, the function is a higher-order function.

1 def S_int (n): 2     return int (n) 3 def add (x, y, z): 4     Print (z (x) +z (y))        # Z is a function that passes the value of x, y to Z and then the Z function to add two values 5 Add ('2','3', S_int)

3. Nesting functions

A nested function is to define a function inside a function, and note that a function is defined rather than a function.

1 def test1 (): 2     def test2 (): 3         Print ('test2') 4     Print ('test1') 5     test2 ()6 test1 ()

4, the decorative device

Decorator is actually a decorative function, its role is to add new functions to other functions, but does not change the original function call mode;

The following is a function of the call time of a statistic function, which, by means of the adorner, statistics the running time without changing the method of the original function Call.

1 Import time2 deftest1 (func):3     defDeco ():#run-time calculations for this function4Start_time =time.time ()5 func ()6Stop_time =time.time ()7         Print('the func Run time is%s'% (stop_time-Start_time))8     returnDeco#returns the Deco variable after the function is run9@test1#call an adorner, in front of a function that requires time to be countedTen defBar (): oneTime.sleep (2) a     Print('In the bar') -Bar ()#when the function is called, the decoration function is performed, and the elapsed time is Counted.

5. Recursive functions

A subset of functions calls itself a recursive function, and a function can call itself up to 999 times, so it has to have a definite end condition and the efficiency of another recursive function

Not high, try to use Less.

1 defTest ():2num = int (input ('please Enter a num:'))3     ifnum%2 = =0:4         returnTrue5     Else:6         Print('non-even, Please re-enter')7Test ()#can play a role in the loop8Test ()

6. Built-in Functions

Python default-defined functions

1 #Forcing type conversions2bool's')#BOOL Type3int ()#Plastic Surgery4Float ()#decimal5STR ()#string6Dict ()#Dictionary7List ()#List8Set ()#Collection9Tuple ()#Meta-groupTen  one Print(dir (1))#to print a callable method of an incoming object a Print(eval ('[]'))#Execute Python code, only perform simple, define data types and operations - Print(exec('def a ():p'))#Execute Python code -  theFilter (func,[1,2,3,4])#according to the previous function processing logic, sequentially processing each element in an iterative recall -                               #returns True to return the - Print(list (filter (func,[1,2,3,4)))#Invocation Mode -Map (func,[1,2,3,4])#according to the previous function processing logic, the subsequent iteration of the object can be iterated within each element +                               #Save all results returned by the previous function - Print(locals ())#return local Variables + Print(globals ())#returns all global variables, returns a dictionary a Print(max (111,12))#Take maximum value at Print(round (11.11,2))#take a few decimals - Print(sorted ([2,31,34,6,1,23,4]))#Sort - Print(sorted (dic.items ()))#sort by key in the dictionary - Print(sorted (dic.items (), key=LambdaX:x[1]))#sort by the value of the dictionary

7. Module

The module is actually a Python file, the essence of the import module is to execute the Python file from beginning to end

#模块导入方式
Import OS #方法一, importing the entire module
os.path.exists (' xxx ') #调用os下的函数

From OS import path #方法二, call a function directly under the OS

From Day5.model import Hello #导入day5文件夹下的model文件中的hello方法
Hello ()

Random module

1 ImportRandom2 Print(random.random ())#random floating-point number, default 0-1, cannot specify range3 Print(random.uniform (1, 5))#Random floating point number, You can specify the range4 Print(random.randint (1, 20))#random integers5 Print(random.randrange (1, 20))#randomly produces a range6 Print(random.choice ([1,2,3,4,5]))#randomly take an element7 Print(random.sample ([1,2,3,4,'6'], 3))#randomly fetching several elements from a sequence, returning a list8x = [1, 2, 3, 4, 5, 6]9Random.shuffle (x)#shuffle, Scramble order, Change the value of the original list

JSON module

JSON and Python dictionary types, but JSON can only be double quotes, not single quotes, can be used in online format validation to determine the Format.

1 Import JSON 2 3 Print (json.dumps (DIC))      # turn the dictionary into a JSON string 4 Print (json.loads (S_JSON))   # convert a JSON string into a dictionary 5 6 Print (json.dump (dic, f))  # translate the dictionary into a JSON string to write to a file 7 Print (json.load (f))  # read the JSON data from the file and turn it into a dictionary

Python--function (ii), adorner,

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.