gaofeng0210 发表于 2017-4-30 15:02:49

Python基础教程笔记——抽象

抽象

Table of Contents


[*]1 懒惰即美德
[*]2 抽象和结构
[*]
3 创建函数

[*]3.1 给函数创建文档(Documenting Function)
[*]3.2 并非真正函数的函数


[*]
4 参数魔法

[*]4.1 值从哪里来
[*]4.2 能够改变参数吗
[*]4.3 关键字参数和默认值
[*]4.4 收集参数
[*]4.5 函数收集逆过程


[*]5 作用域
[*]
6 递归

[*]6.1 阶乘
[*]6.2 幂
[*]6.3 二元查找








1 懒惰即美德


[*]例子:
1:#Fibonacci数列函数
2:def fibo(x):
3:      if x < 2:
4:          return;
5:      result =
6:      for i in range(x - 2):
7:          result.append(result[-1] + result[-2])
8:      return result;
9:
10:#测试
11:myarray = fibo(10)
12:print(myarray)
13:input("Press enter!")      
14:
15:#结果
16:>>>
17:
18:Press enter!
19:>>>
20:





2 抽象和结构


[*]说明:抽象可以节省很多工作,是计算机程序让人读懂的关键;





3 创建函数


[*]说明:
[*]函数是可以被调用的,它执行一些操作并返回一个值,可以使用内 建函数 callable 判断函数是否可以被调用;
[*]使用 def 语句定义函数;
[*]
return 语句用来返回值;


[*]例子:
1:#没有导入math模块,用callable判断函数是否可用
2:>>> callable(math.sqrt)
3:Traceback (most recent call last):
4:    File "<pyshell#9>", line 1, in <module>
5:      callable(math.sqrt)
6:NameError: name 'math' is not defined
7:#导入math模块
8:>>> import math
9:>>> callable(math.sqrt)
10:True
11:>>>
12:
13:#创建函数
14:>>> def myfunc(myparam):
15:          print("This is my func!")
16:          return 'Finish'
17:
18:#调用函数
19:>>> myfunc('Test')
20:This is my func!
21:'Finish'
22:>>>
23:



3.1 给函数创建文档(Documenting Function)


[*]说明:在函数开头添加一个字符串,它会随函数一同保存,这个字符串被 称为文档字符串;
[*]例子:
1:#定义函数,并在里面添加文档字符串(docstring)
2:>>> def TestDocstring():
3:          '这是一个文档字符串,它会随函数一同保存'
4:          print('Hello, world!')
5:          return 0
6:#调用函数
7:>>> TestDocstring()
8:Hello, world!
9:0
10:#使用内置的help函数可以显示函数中的文档字符串
11:>>> help(TestDocstring)
12:Help on function TestDocstring in module __main__:
13:
14:TestDocstring()
15:      这是一个文档字符串,它会随函数一同保存
16:
17:>>>
18:





3.2 并非真正函数的函数


[*]说明:有些函数只执行一些操作,不用向调用方返回值,这时函数定义时, 可以省略return语句;
[*]例子:
1:#不含return语句的函数
2:>>> def myfunc():
3:          print("Hello")
4:
5:
6:>>> myfunc()
7:Hello
8:
9:#含return语句的函数
10:>>> def myfunc1():
11:          print("Hello")
12:          return
13:
14:>>> myfunc1()
15:Hello
16:
17:>>> result = myfunc()
18:Hello
19:#result结果为空对象
20:>>> print(result)
21:None
22:>>> result = myfunc1()
23:Hello
24:#result结果为空对象
25:>>> print(result)
26:None
27:>>>
28:







4 参数魔法

 


4.1 值从哪里来


[*]说明:
[*]创建函数时应该保证在收到合法参数时,执行正确的操作,收到非 法参数时,执行明显的异常(一般通过断言(assert)或者异常 (exception)来实现);
[*]形式参数(formal parameters):在函数定义中的参数;
[*]实际参数(actual parameters):在调用时的参数;


[*]例子:
1:#name为形式参数
2:>>> def hello(name):
3:          print("Hello, %s!" % name )
4:
5:
6:#'Bill'为实际参数
7:>>> hello('Bill')
8:Hello, Bill!
9:>>>
10:





4.2 能够改变参数吗


[*]说明:在函数内为参数赋与新值不会改变外面任何变量的值;
[*]注意:如果参数是列表,那么如果函数中修改了参数,也将修改原列表, 为了避免这种情况,可以使用分片来传递参数;
[*]例子:
1:#函数不修改参数值
2:>>> def myfunc(x):
3:          x=10
4:          return
5:
6:>>> x = 5
7:>>> myfunc(x)
8:>>> x
9:5
10:>>>
11:
12:#如果参数是列表,那么在函数中如果修改了参数,也会影响到调用的列表
13:>>> def editList(l):
14:          l = 'Test'
15:          return
16:
17:>>> l = ['a', 'b', 'c']
18:>>> l
19:['a', 'b', 'c']
20:>>> editList(l)
21:>>> l
22:['Test', 'b', 'c']
23:>>>
24:
25:#以分片的方式修改列表
26:>>> l
27:['a', 'b', 'c']
28:>>> def editList(l):
29:          l = 'Test'
30:          print (l)
31:          return
32:
33:>>> editList(l[:])
34:['Test', 'b', 'c']
35:>>> l
36:['a', 'b', 'c']
37:>>>





4.3 关键字参数和默认值


[*]说明:
[*]关键字参数:在调用函数时,在实参中指定实参对应的形参,这种调用 中的实参称为关键字参数;
[*]位置参数:在调用函数时,通过位置匹配实参和形参,这种调用中的 实参称为位置参数;


[*]注意:
[*]关键字参数可以在函数中给参数提供默认值;
[*]位置参数和关键字参数可以联合使用,但是应该 避免 使用这种方 式;


[*]例子:
1:#关键字参数
2:>>> def hello(greeting='Hello', name='world'):
3:          print("%s, %s" % (greeting, name))
4:          return
5:
6:#调用时不提供默认值,则调用后,直接使用函数定义中的默认值
7:>>> hello()
8:Hello, world
9:
10:#没有指明形参名,则打印时按位置参数方式调用
11:>>> hello('Nice to meet you', 'Bill')
12:Nice to meet you, Bill
13:>>> hello('Bill', 'Hello')
14:Bill, Hello
15:
16:#使用关键字参数,调用时用关键字匹配,与位置无关
17:>>> hello(name='Bill', greeting='Nice to meet you')
18:Nice to meet you, Bill
19:>>>
20:





4.4 收集参数


[*]说明:
[*]星号+参数名:参数前的星号将所有值放在同一个 元组 中,可以说 是将这些值收集起来,然后使用;
[*]两个星号:用于处理关键字参数,可以将关键字参数收集到同一个字 典;


[*]注意:调用时如果不提供任何元素,则收集参数就是一个空元组或空字典;
[*]例子:
1:#星号+参数,将参数收集到元组中
2:>>> def TestStar(x, *params):
3:          print(x)
4:          print(params)
5:          return
6:
7:>>> TestStar(1, 2,3,4,5)
8:1
9:(2, 3, 4, 5)
10:
11:#两个星号,将参数收集到字典中
12:>>> def TestDoubleStar(x, **params):
13:          print(x)
14:          print(params)
15:          return
16:
17:>>> TestDoubleStar(x=1,y=2,z=3)
18:1
19:{'y': 2, 'z': 3}
20:>>>
21:





4.5 函数收集逆过程


[*]说明:将实际参数放入元组或者列表,再调用函数的过程;
[*]注意:使用一个星号来传递元组,使用两个星号来传递字典;
[*]例子:
1:#传递元组
2:>>> def myAdd(x, y):
3:          return x+y
4:
5:>>> data=(1231, 2131)
6:>>> myAdd(*data)
7:3362
8:>>>
9:
10:#传递字典
11:>>> def myHello(greeting, name):
12:          print('%s, %s' % (greeting, name))
13:          return
14:
15:>>> data={'name':'Bill Gunn', 'greeting':'Hello'}
16:>>> myHello(**data)
17:Hello, Bill Gunn
18:>>>
19:







5 作用域


[*]说明;在函数内声明的变量,都是局部变量,如果需要在函数内声明全局 变量,需要在声明前添加关键字 global
[*]例子:
1:#局部变量
2:>>> def TestLocalParam():
3:          x = 10
4:          return
5:
6:>>> x
7:Traceback (most recent call last):
8:    File "<pyshell#4>", line 1, in <module>
9:      x
10:NameError: name 'x' is not defined
11:
12:#全局变量
13:>>> y = 10
14:>>> def TestGlobalParam():
15:          global y
16:          y = 100
17:          return
18:>>> y
19:10
20:#使用函数修改全局变量
21:>>> TestGlobalParam()
22:>>> y
23:100
24:>>>      
25:





6 递归

 


6.1 阶乘


[*]例子:
1:>>> def factorial(n):
2:          if n < 1:
3:                  return 0
4:          elif n == 1:
5:                  return 1
6:          else:
7:                  return factorial(n-1) * n
8:
9:
10:>>> x = factorial(2)
11:>>> x
12:2
13:>>> factorial(3)
14:6
15:>>> factorial(4)
16:24
17:>>> for i in range(10):
18:          print(factorial(i))
19:
20:
21:0
22:1
23:2
24:6
25:24
26:120
27:720
28:5040
29:40320
30:362880
31:>>>
32:





6.2 幂


[*]例子:
1:>>> def mypow(x, y):
2:          'y must be positive integer'
3:          if y == 0:
4:                  return 1
5:          else:
6:                  return x * mypow(x, y-1)
7:
8:>>> mypow(0, 10)
9:0
10:>>> mypow(1, 10)
11:1
12:>>> mypow(2, 10)
13:1024
14:>>> mypow(2, 128) * 0.0002
15:6.80564733841877e+34
16:>>>      
17:





6.3 二元查找


[*]例子:
1:>>> def binSearch(sequnce, number, lower, upper):
2:          if lower == upper:
3:                  assert number == sequnce
4:                  return upper
5:          middle = (lower + upper) // 2
6:          if number > sequnce:
7:                  return binSearch(sequnce, number, middle+1, upper)
8:          else:
9:                  return binSearch(sequnce, number, lower, middle)
10:
11:
12:>>> x
13:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
14:22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
15:41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
16:60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
17:79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
18:>>> binSearch(x, 10, 0, 99)
19:10
20:>>> binSearch(x, 11, 0, 99)
21:11
22:>>>
23:








Date: 2011-12-02 14:37:46
Author:
Org version 7.7 with Emacs version 23

Validate XHTML 1.0
页: [1]
查看完整版本: Python基础教程笔记——抽象