Python-based functions

Source: Internet
Author: User

Python-based functions

We can use a piece of code to implement the functions we need, but when we need to reuse this code, copying and pasting is not a cool method. We can use functions to achieve this requirement.

I. Function Definition

A function is a logical structured and procedural programming method. A function name encapsulates a string of code used to complete a specific function.

Function Definition:

Def function name (parameter 1, parameter 2 ....):

''Comment''

Function body

Def func1 (): # define the function print ('this is a function') # function body func1 () # Call a function
# Generally, no return value is required for a function without any parameters.
Def func1 (name): # print ('% s is a good man' % name) func1 ('egon') with Parameters ')
# If the return value of the function is not specified, the default value is None.
# The definition of a function and a process is that the process does not return values, but does not return values after use.
Def func1 (name): print ('% s is a good man' % name) print (func1 ('egon '))

--> Egon is a good man

None

Advantages of functions: 1. code reuse

2. Maintain consistency and ease of maintenance

3. good scalability

Note: 1. The function must be defined first. When used, it is similar to a variable. If used before definition, an error is returned.

2. During the definition phase, the function only detects syntax errors and does not execute code. Therefore, even if there are undefined variable names in the function, no error will be reported before the function is called.

3. the return value of the function can be of any type. If multiple values are returned, they must be in the form of tuples.

4. The function of return is to terminate the execution of the function. return is executed only once, and subsequent content is not executed.

Ii. Function Parameters

Function parameters are classified into formal parameters and actual parameters. When a function is defined, formal parameters are enclosed in brackets. When a function is called, the parameters passed are actual parameters. The format parameter is valid only within the function and cannot be referenced from outside.

1. Parameters

1) location parameters: the def foo (x, y, z) parameters are defined from left to right)

The location parameter must be passed in, and one or more parameters will not work.

2) default parameter: The parameter has been assigned a value in the function definition phase. If the parameter is not assigned a value in the call phase, the default value def foo (x, y = 10) is used)

When the value changes frequently, it is usually defined as a location parameter, but the value remains unchanged in most cases, it can be defined as a default parameter.

Note:

A. default parameters must be placed after the Location Parameter

B. default parameters are usually defined as unchangeable types.

C. default parameters are assigned only once during definition.

3) name keyword parameter: The shape parameter defined after def register (*, name, age) * must be passed a value and must be passed a value in the form of a keyword.

2. Real Parameters

1) location parameters: one-to-one correspondence with location parameters

2) keyword parameter: when defining a real parameter, it is defined in the form of key-values.

Def foo (x, y)

Foo (x = 1, y = 2)

Keyword parameters do not need to correspond to the shape parameters in the same way as the location parameters, but they can break the order restrictions.

Note: When a. Location Parameter and keyword parameter are used together, the location parameter must be prior to the keyword Parameter

B. It can be in the form of a positional real parameter or a keyword real parameter, but only one parameter can be passed a value once.

3) variable length parameters:

The variable length parameter defined by location is represented *.

Variable type parameters defined by keywords are represented **

def func(x,y,*args):    print(x,y,args)func(1,2,3,4,5)  --->1 2 (3 4 5)

# When * is a location parameter, all the parts after * are split and matched one by one. The excess parts are stored in the form of tuples.

def func(x,y,**kwargs):    print(x,y,kwargs)func(1,y=2,z=3,a=1,b=2)---->1 2 {'z': 3, 'a': 1, 'b': 2}

# If ** is a keyword parameter, all the keywords following ** are split into keywords and matched one by one. Additional keywords are stored in dictionary form.

Def wrapper (* args, ** kwargs): parameters of any form and length can be accepted.

The order in which parameters are defined: x, y = 1, * args, z, and ** kwargs, which are respectively location parameters, default parameters, variable length location parameters, named keyword parameters, and variable type parameters.

However, you must note that these parameters do not all appear at the same time.

Iii. namespace and scope

The namespace stores the binding relationship between names and values in the form of key-value.

In the Windows Command Prompt line, enter the command: import this, and you will see the following sentence in the last line:

Namespaces are one honking great idea -- let's do more of those!

There are three types of namespaces:

1) built-in namespace: Python built-in namespace, such as print, int, len... will be generated when the Python interpreter is started.

2) global namespace: The name defined at the file level is stored in the global namespace. It is generated when a Python program is executed. Simply put, it is a variable name without indentation.

3) local namespace: The name defined in the function (or module or class). It takes effect only when the function (module or class) is called and is released after the call is completed.

The loading sequence is: built-in namespace --> global namespace --> local namespace

The value order is: local namespace --> global namespace --> built-in namespace

Iv. Function nesting and scope

1. Function nesting includes nested call of functions and nested definition of functions

The following example shows how to calculate the maximum value for nested function calls:

def max2(x,y):    if x > y:        return x    else:        return ydef max4(a,b,c,d):    res1=max2(a,b) #23    res2=max2(res1,c) #23    res3=max2(res2,d) #31    return res3print(max4(11,23,-7,31))

Nested Function Definition:

def f1():    def f2():        def f3():            print('from f3')        print('from f2')        f3()    print('from f1')    f2()# print(f1)f1()

2. Scope

1) global scope: The names of the built-in and global namespaces belong to the global scope and can be referenced anywhere in the entire file.

2) local scope: it belongs to a local scope and can be referenced only within the function. It is partially valid.

Be sure to pay attention to the scope of the local variables and global variables. An error occurs when you modify the global variables locally and when you reference the local variables globally.

The scope is fixed when the function is defined and will not be changed because of the call location.

However, if you must modify global variables locally, you can add a global

x=1def foo():    x=10    print(x)        foo()       #10print(x)    #1
x=1def foo():    global x    x=10    print(x)foo()       #10print(x)    #10
Def foo (): x = 1 def f2 (): x + = x return f2 () print (foo () # The following error occurs: local variable 'X' referenced before assignmentdef foo (): x = 1 def f2 (): nonlocal x # Tell the Python interpreter that x is not a local variable, only the internal function will be searched, and the global variable x + = x return f2 () print (foo () # The MODIFIED x value will be printed. 2

5. Closure Functions

A function defined within a function. An internal function contains a reference to an external scope rather than a global scope name. Therefore, this internal function is called a closure function.

Name = 'egon' def func (): name = 'Alex 'def bar (): print (name) return barf = func () # f is the closure function
Print (f. _ closure _ [0]. cell_contents) # This command can be used to check what is out of the closure function ------> alex

Features of the closure function: a. built-in scope, B. Delayed computing (f only gets the memory address of the function, and when to use it, it can be run with parentheses)

The most basic form of closure functions:

Def external function name ():

Variables required by internal functions

Def internal function name ():

Reference external variables

Return internal function name

6. decorator

1. Open and closed principle: it is open to expansion and closed to modification.

2. the decorator is essentially any callable object, and the decorated object is also any callable object.

3. The function of the decorator is to add new functions to the decorator without modifying the source code and calling method of the decored object.

4. decorator Syntax: Write @ decorator name in a separate line above the decoration object

5. When there are multiple decorators, one in each line will run from top to bottom.

6. If the decorated function has parameters: it is written in the form of (* args, ** kwargs)

Decorator Example 1:

# Implement the cache webpage content function. The downloaded page is stored in the file. If there is a value in the file (the size of the file is not 0), # Read the webpage content from the file first. Otherwise, download the file and save it to the file from urllib. request import urlopenimport oscache_path = r 'C: \ untitled \ 0615Python 8th days \ cache_file.txt 'def make_cache (func): def wrapper (* args, ** kwargs): if OS. path. getsize (cache_path): # cache print ('\ 033 [45 m ========> cache \ 033 [0m') with open (cache_path, 'rb') as f: res = f. read () else: res = func (* args, ** kwargs) # download with open (cache_path, 'wb') as f: # create cache f. write (res) return res return wrapper @ make_cachedef get (url): return urlopen (url ). read () print (get ('https: // www.python.org '))

Decorator Example 2:

# Add the authentication function for multiple functions (the user's account and password come from the file). The login is required to be successful once, and subsequent functions do not need to enter the user name and password db_dic = {'egon ': '200', 'Alex ': 'alex3714', 'yuanhao': 'smallb'} db_path = r 'C: \ untitled \ 0615Python 123 days \ db_dic.txt' with open (db_path, 'w', encoding = 'utf-8') as f: f. write (str (db_dic) login_dic = {'user': None, 'status': False,} def auth (func): def wrapper (* args, ** kwargs ): # Add a dictionary of verification status. if you have successfully logged on, you do not need to re-verify if login_dic ['user'] and login_dic ['status'] For the next use. res = func (* args, ** kwargs) return res else: name = input ('name: ') password = input ('password:') with open (db_path, 'R', encoding = 'utf-8') as f: auth_dic = eval (f. read () if name in auth_dic and password = auth_dic [name]: print ('login OK ') login_dic ['user'] = name login_dic ['status'] = True res = func (* args, ** kwargs) return res else: print ('error ') return wrapper @ authdef index (): print ('welcom to the page') @ authdef home (name): print ('welcom to % s \'s home page' % name) index () home ('egon ')

VII. iterator

1. For the Data Types of strings, lists, and tuples, we can implement iteration Based on indexes. However, for the data types without indexes such as dictionaries and sets, other methods are required.

2. In order to provide an index-independent iteration method, Python has built-in _ iter _ Method for some objects. The result of obj. _ iter _ () is the iterator.

The obtained iterator contains both the. _ iter _ method and the. _ next _ method.

3. Advantages of the iterator:

A. Provides an index-independent value method.

B. inert computing, saving memory

4. disadvantages of the iterator:

A. The value is not as convenient as the index value.

B. The value can only be backward and cannot be backward.

C. The iterator length cannot be obtained.

5. The for loop actually calls the. _ iter _ method by default.

6. Determine whether the object and iterator can be iterated. You can use the command

Print (isinstance (str1, Iterable) ---> determine whether the object can be iterated

Print (isinstance (str1, Iterator) ---> judge whether it is an Iterator

VIII. Generator functions (statement form and expression form)

1. Generator function: the function contains the yield keyword. The execution result of this function is the generator.

2. the generator is actually a type of iterator.

3. yield features:

A. Similar to return, return values can be returned, but the difference is that yield returns multiple values, while return can only return one value.
B. encapsulate the _ iter _ and _ next _ methods for the function, and make the function execution result into an iterator.
C. Follow the iterator's Value Method obj. _ next _ () to trigger the execution of the function. The pause and resume statuses of the function are saved by yield.
4. Example of generator statement form application

1 # simulate the function of tail-f a.txt | grep 'error' | grep '000000' in linux 2 import time 3 def tail (filepath, encoding = 'utf-8 '): 4 with open (filepath, encoding = 'utf-8') as f: 5 f. seek (0th) # Start with the end, 6 while True: 7 line = f. readline () 8 if line: 9 yield line10 else: 11 time. sleep (0.5) 12 13 def grep (lines, pattern): 14 for line in lines: 15 if pattern in line: 16 # print (line) 17 yield line18 19 g1?tail('a.txt ') 20 g2 = grep (g1, 'error') 21 g3 = grep (g2, '000000') 22 23 for I in g3: 24 print (I)
View Code

5. Generator Expression Form

Def foo (): print ('starting') while True: x = yield # The default value is yield None print ('value: ', x) g = foo () next (g) # initialization, equivalent to g. send (None) g. send (2)

Assign the yield value to a variable such as x = yield and then use send () to pass the value. However, you must first perform initialization-like operations.

G. the send (2) operation is to first pass 2 to yield, and then pass the value to x. send () has both the effect of passing values and the effect of next ().

Example of application in generator Expression Form

1 def init (func): 2 def wrapper (* args, ** kwargs): 3g = func (* args, ** kwargs) 4 next (g) 5 return g 6 return wrapper 7 @ init 8 def eater (name): 9 print ('% s ready to eat' % name) 10 food_list = [] 11 while True: 12 food = yield food_list # return None13 food_list.append (food) 14 print ('% s start to eat % s' % (name, food )) 15 16 17 e = eater ('Alex ') 18 print (e. send ('shit ') 19 print (e. send ('maosh') 20 print (e. send ('Alex Sh') 21 22 23 def make_shit (people, n): 24 for I in range (n): 25 people. send ('shit % s' % I) 26 27 e = eater ('Alex ') 28 make_shit (e, 5) 29 # from egon30 # The egon example has a taste, but I can't help it.
View Code

9. Ternary expressions

Res = x if x> y else y -----> determine whether condition x> y is true. if it is true, x is assigned to res. Otherwise, y is assigned to res.

10. List Parsing

s='hello'res=[i.upper() for i in s]print(res)          #['H', 'E', 'L', 'L', 'O']

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.