当前位置:   article > 正文

我的python学习日记3(函数默认值、关键字、参数为**name的函数调用)_python **name

python **name

函数默认值只会执行一次,在默认值为可变对象(如列表、字典以及大多数类实例)时很重要。函数会存储在后续调用中传递给它的参数。

  1. def f(a, L=[]):
  2. L.append(a)
  3. return L
  4. print(f('fofo '))
  5. print(f('Bonne nuit '))
  6. print(f('!!!!'))

执行结果如下:
['fofo ']
['fofo ', 'Bonne nuit ']
['fofo ', 'Bonne nuit ', '!!!!']

显然函数存储了后续调用传入的参数。若不希望调用之间共享默认值,可以使用关键字None

  1. def f(a,L=None):
  2. if L is None:
  3. L=[]
  4. L.append(a)
  5. return L
  6. print(f(123))
  7. print(f(1))

执行之后就不会有共享调用参数的情况。

关于参数函数的调用:

  1. def showpar(vule,stata = 'the striff',action = 'boom',type = 'Blue'):
  2. print('-- This showpar wouldn\'t',action,' ')
  3. print('if you put ',vule,'that will be show!')
  4. print('And show the type is ',type)
  5. print('--It\'s',stata,'!')
  6. showpar(1000)
  7. showpar(2000,action='fun')


当存在一个形式为**(name1)的最后一个形参时,它会接收一个字典,包括了除与已有形参相对应的关键字参数以外的所有关键字参数。这可以与一个形式为*(name2)一起接收一个包括除了已有形参列表以外的位置参数的元组形式的形参。

  1. def cheeseshop(kind, *arguments, **keywords):
  2. print("-- Do you have any", kind, "?")
  3. print("-- I'm sorry, we're all out of", kind)
  4. for arg in arguments:
  5. print(arg)
  6. print("-" * 40)
  7. for kw in keywords:
  8. print(kw, ":", keywords[kw])
  9. cheeseshop("Limburger","It's very runny, sir.",
  10. "It's really very, VERY runny, sir.",
  11. shopkeeper="Michael Palin",
  12. client="John Cleese",
  13. sketch="Cheese Shop Sketch")

运行结果为:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

使用了for对导入的元组进行输出元组不一定要是字符串也可以是数字。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/41390
推荐阅读
相关标签
  

闽ICP备14008679号