Day Four: Functions


## a, how to define the function

`` `Python
'' '
simplification 1, function
2, an internal function resources required external: realized by function parameter
3, the result of function execution need to tell the outside world: tell the outside world through the return value of
' ''
` `

 

## Second, the parameters of the function

Types of actual parameter ####

Python `` `
'' '
parameter: Parameter () appeared at the function definition
- does not have the actual parameter value (meaning), when the function is invoked, passing what arguments, with a reference to what value
argument: parameter () that appears in the function call
- arguments have practical value (meaning)

Key: function call parameter passing: the value assigned to the argument of the parameter | parameter to get the value of the outside world only through argument for obtaining
'' '

def fn(a, b): # a, b:形参
pass

= 10 A
Fn (A, 20) # A, 20:实参

```

#### two kinds of arguments

Python `` `
'' '
position of the argument:
1. parameter passing in two ways: the name argument | particular argument value
2 must be passed a position parameter value


Keyword argument:
1. The parameter passing in two ways: the parameter name argument name = | parameter name argument value =
2. The parameter may be passed to name names value, it can not be transmitted by the reference position
' ''

def func(a, b, c):
print(a, b, c)

# Func (10, b = 20 , 200) being given: SyntaxError: Positional argument Follows keyword argument
# Key: two kinds of reference arguments together for transmission when: must first position, after the keyword
`

 

#### Two parameter classification

Python `` `
'' '
parameter types:
1) the position parameter
- the normal position parameter
- the default parameter
- the position of the variable length parameter

2) key parameter
- the parameter has a default value of the key
- no default parameter keyword
- the keyword variable length parameter
'' '
DEF Fn (A, B, *, X, Y): # parameter position: a, b keyword parameter: X, Y
Pass

'' '
Key:
1. * watershed
2. The position parameter can be passed argument values to the position of the finger
3. Keyword argument can participate to the position of the finger key parameter values passaged
' ''
`

 

Two shape parameters with default values ​​####

Python `` `
DEF Fn2 (A = 10, *, X = 20 is):
Print (A, X)
Fn2 (100, X = 200 is)
# Summary:
# 1 has a default value of the parameter values can not pass
# 2. * before the call has a default value of the default value of the parameter, a position parameter belongs, a position value can be passaged and keywords argument
# 3 * has called default values that have default values after the key parameter, are key-shaped ginseng, is subjected to only a keyword argument passed by value
# * 4. If omitted, the default value of the parameter with a shape is the default value of the parameter

```

 

#### with no default value and the default value parameter in combination with

`` `Python
DEF Fn3 (A, B = 10, *, X, Y = 20 is, Z):
Print (A, B, X, Y, Z)
Fn3 (100, X = 200 is, Z = 300)
# summary :
# 1. there is no default value must pass parameters, with default values may or may not pass pass
# 2 position has a value of no value must appear after the keyword order not required
`` `

 

#### variable-length position between Form variable length parameter keywords

Python `` `
DEF Fn4 (A, B = 10, * args, X, kwargs **):
Print (A, B, X)
Print (args)
Print (kwargs)
Fn4 (10, 20 is, 30, X = 100 , Y = 200 is, Z = 300)
# summary:
# 1 is used to receive the variable length value is not completely received (received 0 to n):
# - * args receive all positions not finished receiving ( can only receive location argument)
# - ** kwargs to receive all of the keywords not finished receiving (reception only keyword argument)
# 2. * args must appear so after positional parameters, ** kwargs must appear after so parameters


Common application scenario #
# always assume that the first position is a parameter name
DEF Func4 (* args, ** kwargs):
name = args [0] # The name out to

func44 DEF (name, * args, ** kwargs):
# name can directly receive, process out of the province to the
Pass
`` `

 

#### to sum up

Python `` `
'' '
1. argument position can only pass the position parameter value
2. Keyword argument to the location and keywords can pass parameter value
3 has a default value of the parameter can not pass
4. Variable length position parameter argument can receiving position, the receiving position after receiving no parameter argument position, stored in the tuple
5. the variable length key parameter argument can accept keyword, the keyword acceptance parameter keyword argument is not completely received, stored in the dictionary
6. * args must occur after all positions parameter, ** kwargs parameter must after all
'' '
`

 

#### variable-length overall pass parameters: value-passing break

Python `` `
DEF Fn (* args, ** kwargs):
Print (args, kwargs)

Fn ([. 1, 2,. 3], { 'A':. 1, 'B': 2}) = #> received the ([. 1, 2,. 3], { 'a':. 1, 'B': 2})} {
Fn (* [. 1, 2,. 3], {** 'a':. 1, 'B': 2}) = #> received (1, 2, 3) { 'a': 1, 'b': 2}

# Note: string may be broken up as a separate set of transmission
Fn (* 'ABC') # => ( 'A', 'B', 'C') {}
`` `

 

## Third, the function object

`` Python `
# function name is stored the memory address of the function, to store the memory address of the variable is an object, that is, the function name is the function object

# Function object application scenario
# 1 can be directly referenced
# 2 can be used as the function parameter passing
# 3 as the return value of the function may
# 4 types of elements can be used as a container

# Function body
DEF the Add (N1, n2):
return N1 + n2

def low(n1, n2):
return n1 - n2

def jump(n1, n2):
return n1 * n2

# Completion
DEF computed (N1, n2, the Fn): # the Fn = the Add | Low | Jump
RES = the Fn (N1, n2) # call specific functions
return res

# Feature correspondence relationship
method_map = {# correspondence relationship between commands and function object
'. 1': the Add,
'2': Low,
'. 3': Jump
}

# Acquisition function
DEF get_method (cmd):
IF cmd in method_map:
return method_map [cmd] # return to the Add | Low | Jump
return # When the Add command error, add a default function

True the while:
cmd = INPUT ( 'cmd:')
RES = get_method (cmd) (10, 20 is) # The instruction fetch function and calls the results obtained
Print (RES)
`` `

 

## Fourth, the nested function calls

`` `python
nested function calls #: in an internal function calls another function
# find the maximum of two numbers
DEF max_two (N1, N2):
IF N1> N2:
return N1
return N2

# Find the maximum number of three
DEF max_three (N1, N2, N3):
max = max_two (N1, N2)
return max_two (max, N3)

# Find the maximum number of four
DEF max_four (N1, N2, N3, N4):
max = max_three (N1, N2, N3)
return max_two (max, N4)
Print (max_four (20 is, 50, 30, 50))
` ``

 

 

## V. namespace

`` Python `
# namespaces: memory space to store the name and address of the corresponding relationship between the container
# effect: Due to the limited solve the name duplicate name causes problems sending conflicting - built-in global local store can use a different name at the same time address

# Three kinds namespace
# Built-in: Built-in namespace; system-on-one; with the interpreter to execute and produce, while the interpreter to stop the destruction
# Global: global name space; the file level, more; your file is loaded with produce , file has finished running and destruction
# local: The local name space; function-level, more; with the implementation of your function to generate the function is finished and destroyed

# Load order: Built-in> Free Join> the Local
# - stored in the stack data using the embodiment (push), resulting in built last accessed
`

 

## six nested definitions, function

`` `python
nested definitions # function: the function defined functions inside
reasons # birth: a function wants to use another internal variable function may be defined inside
DEF FUNC ():
10 A =
DEF Fn ():
Print (A)
return Fn

new_fn = func()
new_fn()
```

 

#### with two functions related keywords: global nonlocal

Python `` `
# Global: uniform local and global variable names
NUM = 10
DEF Outer ():
# Global NUM
# NUM = 100
DEF Inner ():
Global NUM
NUM = 1000

# nonlcal: Unity nested local variables and partial name
DEF Outer ():
NUM = 100
DEF Inner ():
nonlocal NUM
NUM = 1000
`` `

 

## Seven, scope

`` Python `
# Scope: The scope name of the function
# effect: to solve the same name can coexist problem - the value of the same name in different scopes can be used in the scope of its scope
'' '
four kinds of scope: LEGB
Built -in: built-in scope - all files in all places can be accessed
global: global scope - in all positions of the current file
Enclosing: nested scopes - Functions within itself and inside the
local: the local scope - only their own internal
'' '
# load order: Built-in> Free Join> Enclosing> the Local
# access (search) the sequence: given <Built-in <Free Join <Enclosing <the Local
# scope: Built-in> Free Join> Enclosing> the Local
`` `

 

## Eight, closures

Python `` `
# closure: defining a function of the internal function, is a function of the internal closure

Application Scene #:
# 1. The internal variables may be used to other functions, and may also invoke the same position assurance (as a function object closure that function return values)
DEF Outer ():
COUNT = 3000
DEF Fn ():
print (count) # can use the variable COUNT inside the Outer
return fn
# or call in outside
outer () () # outer ( ) () => fn () => call fn


Delayed execution # 2 (the outer layer functions as a memory function can pass parameters)
Import Requests
DEF Outer (URL):
DEF show_html ():
Response = requests.get (URL)
Print (response.text)
return show_html

# Making climbing function object Baidu and Sina
show_baidu = Outer ( 'https://www.baidu.com')
show_sina = Outer ( 'https://www.sina.com.cn')

# Delay to the demand, the need to climb Baidu, Baidu to use a function object, you need to climb Sina, Sina will use the function object
show_baidu ()
show_sina ()
show_baidu ()
`` `

 

## September, decorator

Python `` `
# decorator: decorator closures is a scenario
# - using an integrated structure of a closure outer function and memory function formed

# Key: Open Closed Principle
# open: expand the function point is open - you can add new features to the previous function
# closed: 1 can not change the original function of the source code 2. there is a function object to call the original function by function.

Huaping DEF ():
Print ( "flower function ')

= Huaping TEMP
DEF my_huaping ():
TEMP ()
Print ( 'viewing function')
Huaping = my_huaping

huaping ()

# ----------------------------------------

Huaping DEF ():
Print ( "flower function ')

def outer(temp): # temp = huaping
def my_huaping():
temp()
print('观赏功能')
return my_huaping
huaping = outer(huaping) # huaping = my_huaping

huaping ()


---------------------------------------------- #
DEF Outer ( TEMP): # TEMP = Huaping
DEF my_huaping ():
TEMP ()
Print ( 'viewing function')
return my_huaping

# = Outer Huaping @outer (Huaping)
DEF Huaping ():
Print ( 'flower function')

Huaping ()


------------------------------------------ #
# function may have been decorated reference has returned: decorative template to meet all the parameters, and can decorate the original function return value
DEF Outer (FUNC): # the TEMP = Huaping
DEF Inner (* args, ** kwargs):
Pass
RES = FUNC (* args, * kwargs *)
Pass
return RES
return Inner

@outer
def any_method():
pass

```

#### Decorators Case

`` `python
Add account login function test function # is: must be 3 or more letters in English
DEF check_user (FUNC):
DEF Inner (the User, pwd):
IF not (user.isalpha () and len (the User)> . 3 =):
return 'invalid account'
RES = FUNC (User, pwd)
return RES
return Inner

# Add password login function test function: Must be three or more letters or numbers
DEF check_pwd (FUNC):
DEF Inner (* args, ** kwargs):
pwd = args [1]
IF not (pwd.isalnum ( ) and len (pwd)> =. 3):
return 'invalid password'
RES = FUNC (* args, ** kwargs)
return RES
return Inner

# Login result of modification decorator: True => successful login False => Login failed
DEF change_res (FUNC):
DEF Inner (* args, ** kwargs):
RES = FUNC (* args, ** kwargs)
IF RES = True =:
return 'Login successful'
return 'Login failed'
return Inner


Process # decoration is performed from top to bottom
@check_user # = check_user Login (FUNC = Login) = Inner
@check_pwd
@change_res
DEF Login (User, pwd): # function object to be decorated
if user == 'owen' == pwd and '123':
return True
return False

user = input('user: ')
pwd = input('pwd: ')
res = login(user, pwd)

print(res)
```

Guess you like

Origin www.cnblogs.com/michaeldon/p/11327723.html