# Python函数参数总结

# 函数定义
def foo(x, y):
print 'x is %s' % x
print 'y is %s' % y

if __name__ == '__main__':
# 标准调用
foo(1, 2)

# 关键字调用
foo(y = 1, x = 2)

# 标准调用输出
x is 1
y is 2

# 关键字调用输出
x is 2
y is 1

def tax(cost, rate = 0.17):
print cost * (1 + rate)

if __name__ == '__main__':
# rate使用默认值0.17
tax(1000)

# rate指定为0.05
tax(1000, 0.05)

# tax(1000)的输出
1170.0

# tax(1000, 0.05)的输出
1050.0

# 定义函数，其中*theRest为非关键字可变长参数
def tupleVarArgs(arg1, arg2='defaultB', *theRest):
print 'formal arg 1: ', arg1
print 'formal arg 2: ', arg2
for eachXtrArg in theRest:
print 'another arg: ', eachXtrArg

>>> tupleVarArgs('abc')
formal arg 1:  abc
formal arg 2:  defaultB
>>> tupleVarArgs('abc', 'def')
formal arg 1:  abc
formal arg 2:  def
>>> tupleVarArgs('abc', 'def', 'xyz', 123.4)
formal arg 1:  abc
formal arg 2:  def
another arg:  xyz
another arg:  123.4

# 定义函数，其中**theRest为关键字可变长参数
def dictVarArgs(arg1, arg2='defaultB', **theRest):
print 'formal arg 1: ', arg1
print 'formal arg 2: ', arg2
for eachXtrArg in theRest.keys():
print 'Xtra arg %s: %s' % (eachXtrArg, str(theRest[eachXtrArg]))

>>> dictVarArgs('abc')
formal arg 1:  abc
formal arg 2:  defaultB

>>> dictVarArgs('abc', 'def')
formal arg 1:  abc
formal arg 2:  def

# a=1和b='aha'即为关键字可变参数，他们会被放入theRest字典
>>> dictVarArgs('abc', 'def', a=1, b='aha')
formal arg 1:  abc
formal arg 2:  def
Xtra arg a: 1
Xtra arg b: aha

# 全部采用关键字参数，但只有a和b是可变的，会被放入theRest
>>> dictVarArgs(arg2='def', a=1, b='aha', arg1='put at the last')
formal arg 1:  put at the last
formal arg 2:  def
Xtra arg a: 1
Xtra arg b: aha

# 这次使用了arg2的默认值
>>> dictVarArgs('one', a=1, b='aha', name=('yuki', 'lau'))
formal arg 1:  one
formal arg 2:  defaultB
Xtra arg a: 1
Xtra arg b: aha
Xtra arg name: ('yuki', 'lau')

def newfoo(normal_arg1, normal_arg2, *non-keywords, ** keywords):
pass

>>> newfoo(2, 4, *(6, 8), **{'foo': 10, 'bar': 12})

>>> newfoo(2, 4, 3, x=4, y=5, *aTuple, **aDict)

posted @ 2013-05-28 11:48 YUKI小糖 阅读(...) 评论(...) 编辑 收藏