Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19735390
  • 博文数量: 679
  • 博客积分: 10495
  • 博客等级: 上将
  • 技术积分: 9308
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-18 10:51
文章分类

全部博文(679)

文章存档

2012年(5)

2011年(38)

2010年(86)

2009年(145)

2008年(170)

2007年(165)

2006年(89)

分类: Python/Ruby

2009-08-18 08:31:43

抽象

 

懒惰是美德

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

 

抽象和结构

创建函数

>>> 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'

 

参数

       不可变长度的参数不会改变实际参数的值,可变的则会改变。

必须要这样的拷贝:

>>> 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)

 

阅读(2364) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~