- 论坛徽章:
- 0
|
Normal
0
7.8 磅
0
2
false
false
false
MicrosoftInternetExplorer4
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:"Times New Roman";
mso-fareast-font-family:"Times New Roman";
mso-ansi-language:#0400;
mso-fareast-language:#0400;
mso-bidi-language:#0400;}
§6 抽象
§6.1 懒惰是美德
fibs = [0, 1]
for i in range(8):
fibs.append(fibs[-2] + fibs[-1])
>>> fibs
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fibs = [0, 1]
num = input('How many Fibonacci numbers do
you want? ')
for i in range(num-2):
fibs.append(fibs[-2] + fibs[-1])
print fibs
§6.2 抽象和结构
略
§6.3 创建函数
>>> import math
>>> x = 1
>>> y = math.sqrt
>>> callable(x)
False
>>> callable(y)
True
3.0中没有callable函数,要使用:hasattr(func, __call__).
函数定义:
def
hello(name):
return 'Hello, ' + name + '!'
>>> print hello('world')
Hello, world!
def fibs(num):
result = [0, 1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result
函数注释:
def
square(x):
'Calculates the square of the number x.'
return x*x
The docstring
>>> square.__doc__
'Calculates the square of the number x.'
__doc__是函数的特殊属性
无返回值的函数:
def test():
print 'This is printed'
return
print 'This is not'
§6.4 参数
不可变长度的参数不会改变实际参数的值,可变的则会改变。
必须要这样的拷贝:
>>> names = ['Mrs. Entity', 'Mrs.
Thing']
>>> n = names[:]
参数的顺序可变:
>>> hello_1(greeting='Hello',
name='world')
Hello, world!
建议参数较多的时候这样使用。
函数的定义可以使用默认参数:
def
hello_3(greeting='Hello', name='world'):
print '%s, %s!' % (greeting, name)
*号表示吸收后面所有的参数为数组。但是不支持关键字参数。
>>> print_params_3(x=1, y=2, z=3)
{'z': 3, 'x': 1, 'y': 2}
def print_params_4(x, y, z=3, *pospar,
**keypar):
print x, y, z
print pospar
print keypar
This works just as expected:
>>> print_params_4(1, 2, 3, 5, 6,
7, foo=1, bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1, 2)
1 2 3
()
{}
本节的余下部分和实例暂未涉及
§6.5 范围
访问全局变量:
globals()
§6.6 递归
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2030327.html |
|