`
384444165
  • 浏览: 258746 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Beginning Python 笔记学API —— Chapter5 函数

阅读更多

1、函数参数 

 

>>> # 对于函数内不可修改的类型:元组、int、字符串
>>> # 通过将值防止在列表中解决不可变
>>> def inc(x): x[0]=x[0]+1
...
>>> foo = [10]
>>> inc(foo)
>>> foo
[11]

>>> def change(n):
	n= 'new'	
>>> name = 'old'
>>> change(name)
>>> name
'old'

 

2、关键字参数

 

>>> def hello(greeting,name):
	print '%s, %s' % (greeting,name)
>>> hello('hello','world')
hello, world
>>> hello(name='world',greeting='hello')
hello, world

 

3、收集参数

 

>>> def print_params(*params): print params
>>> print_params('Test')
('Test',)
>>> print_params(1,2,3)
(1, 2, 3)

>>> # 收集关键字参数会出错
>>> print_params(params='123')
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    print_params(params='123')
TypeError: print_params() got an unexpected keyword argument 'params'

>>> # 使用**收集关键字参数为字典
>>> def print_params2(*params1,**params2):
	print params1
	print params2
>>> print_params2(1,2,3,p1=3,p2=2)
(1, 2, 3)
{'p2': 2, 'p1': 3}

 

4、反转过程(与收集参数反转)

 

>>> def add(x,y):return x+y
>>> params = (1,2)
>>> add(*params)
3
>>> params = {'name':'jason', 'greeting':'hello'}
>>> hello(**params)
hello, jason

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics