Python learning Essay (vii) _ function

Source: Internet
Author: User
Tags closure function definition generator generator

function #作用: encapsulation and reuse
Mathematical definition: y=f (x), Y is the function of x, and X is the independent variable. Y=f (x0, x1, ..., xn)
Python functions
A statement block, function name, parameter list consisting of several statements, which is the smallest unit of the Organization Code
Complete a certain function

Functions of the function
* Structured programming for the most basic encapsulation of code *, generally according to the function of organizing a piece of code
The purpose of encapsulation in order to reuse *, reduce redundant code
The code is more concise and beautiful, readable and understandable
Classification of functions
Built-in functions such as Max (), reversed (), etc.
Library functions, such as Math.ceil (), etc.

function definition, calling
def statement definition function
def function name (parameter list):
function body (code block)
[Return value]
The function name is the identifier * and the naming requirement is the same
The statement block must be indented, with a contract of 4 spaces
The Python function does not have a return statement, and implicitly returns a value of None
* The parameter list in the definition becomes a * form parameter *, just a symbolic expression, referred to as a formal argument
Call
function definition, just declare a function, it will not be executed, need to call
Called by the function name plus parentheses, the parentheses are written in the arguments
* The parameter written at the time of the call is the actual parameter *, which is the value that is actually passed in, referred to as the argument

defined as a formal parameter, called as an argument, called with parentheses

Python is dynamic, strongly typed language
Because it is dynamic, the parameter does not define the type, which can cause a lot of problems (free industrialization development will bring problems)
The parameter type cannot be restricted unless it is judged
Can you control this? It's a matter of solving the team.

function parameters
Parameters that are passed in when arguments are called match the number of definitions (variable parameter exceptions)
Position parameters
def f (x, Y, z) calls the use F (1, 3, 5) #顺序对应, the number is the same # parameter, pass in the argument
Incoming arguments in order of parameter definition
Keyword parameter #谁等于谁就是关键字传参 (keyword)
def f (x, Y, z) calls use F (x=1, y=3, z=5) #顺序可以不一样, because you can find it by name
Use the name of the formal parameter to enter and exit the argument, and if the parameter name is used, then the order of the parameters can be different from the order of the definition
Pass the reference
F (Z=none, y=10, x=[1])
F ((1,), z=6, y=4.1)
F (y=5, z=6, 2) #位置参数必须在前, keyword in the back is possible
Requires that the positional parameter be passed in before the keyword parameter, which is the position parameter


function parameter Default value #记得时候可以记带等号不可以放前面
Parameter default value (default)
When defined, follow a value after the formal parameter
def add (x=4, y=5):
Return X+y
The test calls Add (6, 10), add (6, y=7), add (x=5), add (), add (y=7), add (x=5, 6) #这个不可以, add (y=8,
4), add (x=5, y=6), add (y=5, x=6)
Test definition The following function def Add (x=4,y) #非缺省跟在非缺省后不可以 (remember when you can remember the equals sign can not be put in front)
Role
The default value of a parameter can be assigned to a default value without a given parameter when sufficient arguments are not passed in
With very many parameters, it is not necessary for the user to enter all parameters each time, simplifying the function call
Example
Define a function login, the parameter name is called host, port, username, password
function parameter Default value


Using * Before the formal parameter indicates that the parameter is a mutable argument and can receive multiple arguments
Collect multiple arguments as a tuple***


mutable type and deconstruction type, but not identical (keyword-only)

DEF fn (*args,x,y,**kwargs)
(x, y) belongs to Keyword-only: You must define the keyword arguments later
You can use the default value, you must use the Keyword argument # to define default values for keyword-only often
def add (*,x,y): #逗号标志后面的是keyword-only


Sum up several types of definition parameters and parameters (defined as formal parameters, called as arguments)
Defining parameters:, positional arguments, variable positional parameters (encapsulated Narimoto group tuple), variable keyword pass-through (encapsulated into Dict dictionary)


Define the parameters: the location of the parameter, the key to the parameter, mixed with the time: the position of the reference in the front, the key word after the argument

Common Position Parameters: both the location and the key parameters are supported, but the position is transmitted to the previous
Variable parameters:
Variable location parameter: keyword cannot be passed and can only be written together to allow variable parameters to correspond to #add (1,2,3,4)

The variable keyword parameter only collects key arguments and cannot be used for positional arguments


Position parameters before placing (variable also to put before), the keyword parameters put (after the star put the stars put the last)

The corresponding parameter must have only one parameter, all the key parameters can not be considered in order


function parameters
Parameter rules
The parameter list parameter General order is, the common parameter, the default parameter, the variable position parameter, the Keyword-only parameter (can with the missing
Save value), variable keyword parameter
Templates: def fn (x, Y, z=3, *arg, m=4, N, **kwargs):
Print (X,y,z,m,n)
Print (args)
Print (Kwargs)


Parametric deconstruction
Can only be used in parameter reference
When the parameter is passed, it is deconstructed and the element is deconstructed as an argument.

Non-dictionary types use * solution to form positional parameters
Dictionary types Use the * * solution to form the keyword parameter
Dictionary deconstruction: A Dictionary of key,** solutions
Add (*{' a ': 5, ' B ': 6}) #解构后为x = ' a ', y = ' B '
#add (**{' a ': 5, ' B ': 6}) #解构后为 ' A ' = 5, ' B ' = 6

Function default return None if you want the function to have return value modify return

--------------------------------------------------------------------------------------------------------------- ---------------------

function return value
Return statement
A function has only one return statement

A multi-branch structure can have multiple return, but only one return
#多分支结构可以设置个变量, the last return variable, can save every branch to write return
If.. ret=. else.. ret=. Last return RET

Functions can return values that can be of different types
A function returns to terminate as soon as it touches a return

Function default return none, often functions need to write return

Return returns must be a value, not one that will be encapsulated into a tuple
Returns multiple value packages in the container to get them using the deconstructed one by one corresponding
--------------------------------------------------------------------------------------------------------------- ------------
Scope * * * *
Nested functions
Functions inside the function cannot be executed externally # because there is no outside definition, the report Nameerror

Functions that are nested within the outer function can be called

# # #函数是有可见范围的, that's the scope

An identifier (variable) inside a function that is not visible externally


The function definition is directly over, and when executed, see if the previous definition uses a variable

Inside the function
x = 5
Def show ():
x + = # error
Print (x)
Show ()

x = x +1 #在函数内部要先定义, otherwise there is no internal definition.
#右边x +1, the assignment is redefined, and the assignment is first to the right,
#右边是内部本地变量 (local scope), X to redefine

Nested functions: Assignment is redefined, but it is a variable that defines itself

Global scope #在整个运行环境中都可见

Local scope (local) #在函数和类等内部中可见

--------------------------------------------------------------------------------------------------------------- ------------
Global scope (understand, write function basic not, change affect too big)
Global x #使用全局作用域变量
#尽可能放在前面第一行

Global uses a local scope to define an action variable in a globally scoped scope
But global only affects the current scope

The function should be used to define formal parameters and to use this form, as far as possible, do not use global

--------------------------------------------------------------------------------------------------------------- ------------

Closed Package * * * #一般在有嵌套函数时候用

Free variable: A variable that is not defined in the local scope. For example, a variable that defines the scope of an outer function outside the memory function

This local variable is used for the inner layer function of the outer layer function, and the closure has been generated


nonlocal keywords
#声明变量不在本地作用域中, but is found in the outer scope, but no longer is found in the global scope
#形成闭包
#一层层向外找但不在全局中找
#不可在全局下一层中用 (because the next layer in the global can be used directly with global variables)
Parameters can be viewed as local variables

--------------------------------------------------------------------------------------------------------------- ------------

Scope of default values

The function is also an object, and if the object contains a reference type, the default value is changed, and the simple type does not change the default value

function name. __defaults__ #查看默认值属性, use tuples to save all positional parameter defaults # using tuple locations will not change
function name. __kwdefaults__ #查看使用字典保存所有keyword The default value of the-only parameter, dict is the keyword argument


Default function defaults to special properties, life cycle and function same cycle

The default value only has its own scope, to see what the default value refers to, if the default value is given to the formal parameter, the scope of the parameter is inside the function, it is local scope of the variable

#default这个东西它又属于函数对象本身的特殊属性, it is placed on a function object.
#函数对象是和函数定义相关的, when a function is defined, its identifier (formal parameter) is associated with the function object created in its memory.


The default scope is the formal parameter, which can be viewed as the local variable of the function.
If the parameter has a variable type (such as a list), there is no fixed default value, and the default value will change.
#有时候这个特性是好的, sometimes this trait is bad and has side effects

def foo (xyz=[], u= ' abc ', Z=123):
Xyz.append (1)
return XYZ
Print (foo (), ID (foo))
Print (foo.__defaults__)
Print (foo (), ID (foo))
Print (foo.__defaults__) #引用类型默认值改变


def foo (xyz=[], u= ' abc ', Z=123):
#xyz = foo.__defaults__
XYZ = xyz[:] # Shadow Copy, Simple Type empty list new generation in memory, memory address different
Xyz.append (1)
Print (XYZ)
Foo ()
Print (foo.__defaults__)
Foo ()
Print (foo.__defaults__)
Foo ([10])
Print (foo.__defaults__)
Foo ([10,5])
Print (foo.__defaults__) #不改变默认值


def foo (xyz=none, u= ' abc ', z=123): #使用不可变类型默认值
If XYZ is None: #使用默认值时创建列表
XYZ = []
Xyz.append (1) # If you pass in a list, modify the list
Print (XYZ)
Foo ()
Print (foo.__defaults__)
Foo ()
Print (foo.__defaults__)
Foo ([10])
Print (foo.__defaults__)
Foo ([10,5])
Print (foo.__defaults__)

The first of these methods
Create a new object with a shadow copy and never change the parameters passed in
The second method of
You can choose to create or modify incoming objects flexibly by judging the value.
This approach is flexible and widely used
Many of the definitions of functions can be seen using the immutable value of None as the default parameter, it can be said that this is a customary method


--------------------------------------------------------------------------------------------------------------- ------------

Variable name resolution principle LEGB #一个名词的查找顺序就是LEGB, one layer to the outside analysis
LEGB specifies the order in which to find a name: local-->enclosing function Locals-->global-->builtin

Local, native scope, local namespace of the domain scope. When a function call is created
Build, call End extinction

enclosing,python2.2, the nested function is introduced, and the closure is implemented.
Is the namespace of the outer function of the nested function

Global scope, which is the namespace of a module. When the module is import
Create, the interpreter exits when extinct

Build-in, built-in module namespace, life cycle starts from the Python interpreter
When it is created, it dies when the interpreter exits. For example, print (open), print and open are built-in variables

--------------------------------------------------------------------------------------------------------------- ------------

Destruction of functions
#函数的定义一般只做一次, unless you want to overwrite it and define it again.
#定义函数的目的就是复用, make it clear why you should destroy it, don't destroy it easily.

Destruction of global functions
Redefine function with the same name
Del statement Delete function object
At the end of the program

Local function destruction
Re-define a function with the same name in the parent scope
Del statement Delete function name, function object reference count minus 1
When the parent scope is destroyed

--------------------------------------------------------------------------------------------------------------- -----------

Recursive functions

#栈和线程相关, the stack is the space of each thread's own
function execution to press the stack, a drop one, the function of local variables to press the stack, after the use of pop-out
#局部变量, when a function call is created, the call ends the extinction

Recursive recursion
A function that calls itself directly or indirectly is recursive.

Recursion must have an exit condition to return a result
return after each calculation


Import Sys
Print (Sys.getrecursionlimit) #查看递归层数

--------------------------------------------------------------------------------------------------------------- ------------

anonymous functions

Format
Lambda parameter list: expression

Map is the generation of a lazy evaluation

(Lambda x:0) (3)
You cannot use an equal sign after a colon
--------------------------------------------------------------------------------------------------------------- ------------
Generator * * * *
Generator generator

Next () #

The generator function must contain a yield statement, and the function body of the generator function will not execute immediately

Co-#非抢占式, polling

Yield from #新语法从可迭代对象中一个个拿元素
For x in range (ten) and yield from range (10)
Yield x


Python learning Essay (vii) _ function

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.