10. Functions

1. Defined Functions

The definition of a function of simple rules:

  • Function block def keyword beginning, followed by the name and function identifier parentheses ().
  • Any incoming parameters and arguments must be placed in the middle of parentheses. Between parentheses may be used to define the parameters.
  • Function first statement can be selectively used documentation string - for storing function instructions .
  • Start function contents colon, and indentation.
  • return [Expression] End function, selectively returns a value to the caller. 不带表达式的return相当于返回 None.
    grammar:
def functionname( parameters ):
   "函数_文档字符串"
   function_suite
   return [expression]

默认情况下,参数值和参数名称是按函数声明中定义的顺序匹配起来的。

2. Function Call

Define a function only as a function of a given name, you specify the parameters, and the block contains a function of the structure.
After completion of the basic structure of this function, you can call the function performed by another, can be executed directly from Python prompt.
Examples

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 定义函数
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
# 调用函数
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");

Results of the:

我要调用用户自定义函数!
再次调用同一函数

3. parameter passing

In 类型属于对象,变量是没有类型的python, :

a=[1,2,3]
 
a="Runoob"

Above, the [1,2,3] is of type List, "Runoob" type String, and 变量 a 是没有类型she is just an object 引用(一个指针), the object can be of type List, can also point to a String object.

3.1 can be changed (mutable) and can not be changed (immutable) objects

In strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象python, .

  • Immutable type : a = 5 Variable Assignment Assignment then a = 10, where actually 新生成一个 int 值对象 10, 再让 a 指向它while 5 is discarded, instead of changing the value of a, is newly corresponds to a.

  • Variable Type : Variable Assignment la = [1,2,3,4] la assignment after the third element [2] = 5 to change the value sucked List la, la in itself did not move, only part of the value of its internal It is modified.

Parameter transfer function:

  • Immutable type : c ++ similarity value transfer, such as 整数、字符串、元组. The value Fun (a), only a transfer of a subject itself has no effect. Such modifications (a) an internal value of a fun, but modify the object copied to another, it does not affect a per se.

  • Variable Type : c ++ similar reference transmission, as 列表,字典. As fun (la), sucked la real pass in the past, the revised fun outside la also be affected

python 中一切都是对象,严格意义我们不能说值传递还是引用传递,我们应该说传不可变对象和传可变对象。
Example pass immutable objects

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def ChangeInt( a ):
    a = 10
 
b = 2
ChangeInt(b)
print b # 结果是 2

Object exemplary variable transmission

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4]);
   print "函数内取值: ", mylist
   return
 
# 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print "函数外取值: ", mylist

Results of the:

函数内取值:  [10, 20, 30, [1, 2, 3, 4]]
函数外取值:  [10, 20, 30, [1, 2, 3, 4]]   #同时都发生了改变

6. Parameters

The following is the formal parameter type can be used when calling the function:

  • Mandatory parameter
  • Keyword arguments
  • The default parameters
  • Variable-length parameters

    6.1 essential parameters

    Necessary parameters to be passed to the function in the correct order. When the number of calls and the same must be declared when.
    Call printme () function, you must pass in a parameter, or will a syntax error:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme();

Results of the:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    printme();
TypeError: printme() takes exactly 1 argument (0 given)

6.2 Keyword parameters

Keyword arguments and function call close relationship function call using keywords to determine the parameters passed in parameter values.
使用关键字参数允许函数调用时参数的顺序与声明时不一致, Because Python interpreter can be matched with the parameter name parameter value.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme( str = "My string");

Results of the:

My string

6.3 default parameters

The function is called, the default value if no incoming parameters is considered to be the default. Under regular printing the default age, if age is not passed:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;
 
#调用printinfo函数
printinfo( age=50, name="miki" );
printinfo( name="miki" );

Results of the:

Name:  miki
Age  50
Name:  miki
Age  35

6.6 variable length parameter

You may need a function that can handle more parameters than the original statement. These parameters, called variable length parameters, and the two kinds of different parameters, not naming declaration. The basic syntax is as follows:

def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

加了星号(*)的变量名会存放所有未命名的变量参数. Examples of variable-length parameters as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print "输出: "
   print arg1
   for var in vartuple:
      print var
   return;
 
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );

Results of the:

输出:
10
输出:
70
60
50

6.7 anonymous function

python using lambda to create an anonymous function.

  • Just a lambda expression, function body is much simpler than def.
  • Lambda expression is a body, instead of a code block. We can only package a limited logic into the lambda expression.
  • lambda function has its own namespace, and can not be accessed outside of its own argument list or the global namespace parameters.
  • Although lambda function looks can only write a single line, but not equivalent to C or C ++ inline functions, which aims not take up the stack memory when calling small functions to increase operating efficiency.

Syntax
The syntax of lambda functions contain only a statement as follows:
【注意:参数后面是冒号(:),不是等号(=)】

lambda [arg1 [,arg2,.....argn]]:expression
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;
 
# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 )
print "相加后的值为 : ", sum( 20, 20 )

Results of the:

相加后的值为 :  30
相加后的值为 :  40

6.8 return statement

return statement [Expression] to exit the function returns a selective expression to the caller. return statement with no parameter values ​​return None.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
def sum( arg1, arg2 ):
   # 返回2个参数的和."
   total = arg1 + arg2
   print "函数内 : ", total
   return total;
 
# 调用sum函数
total = sum( 10, 20 );

Results of the:

函数内 :  30

6.9 Variable Scope

All the variables of a program is not in any position can access. Access depends on where the variable is assigned.

Scope of a variable determines which part of a program in which specific variable names you can access. Two basic variable scope as follows:

  • Global Variables
  • Local variables

Global and local variables
defined as having a local scope, defined outside the function has global scope within a function of the variables.

  • Local variables can only be declared in its 函数内部access
  • Global variables can be 整个程序范围内accessed.

When you call a function, all variables declared within a function name will be added to the scope. Following examples:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
   #返回2个参数的和."
   total = arg1 + arg2; # total在这里是局部变量.
   print "函数内是局部变量 : ", total
   return total;
 
#调用sum函数
sum( 10, 20 );
print "函数外是全局变量 : ", total

Results of the:

函数内是局部变量 :  30
函数外是全局变量 :  0

Guess you like

Origin www.cnblogs.com/QFKing/p/11869284.html