Python中函数支持default value和keyword arguments(类似于C# 4.0中引入的named and optional parameters) . 唯一需要注意的地方就是在一个scope中默认值只会被计算一次,所以如果默认值是可变容器时,要注意side effects.

比如

def f(a, L=[]):

  L.append(a)

  return L

f(1) // return [1]

f(2) // return [1,2]

 

在Python中我们也能常见到这样的函数定义 def f(a, *args,**keyargs), **keyargs是Dictionary类型,对应于*args除外的所有keyword arguments, *args是Tuple类型,对应于所有普通参数除外的positional parameter.

比如 f(1,'1','2', para_name=1)  //a =1, args = ('1','2'), keyargs ={'para_name':1}

 

忘了一点,如果在函数内有object赋值,刚该object被自动视为local object,如果需要的是global object,需显式申明该object为global object.

c = 1

def f():

  c  = c+1 // UnboundLocalError here

需要改为:

c=1

def f():

  global c

  c = c +1

 

 

相关文章:

  • 2021-09-12
  • 2021-10-13
  • 2022-01-02
  • 2021-08-03
  • 2021-11-26
  • 2021-08-30
猜你喜欢
  • 2021-11-19
  • 2021-06-23
  • 2021-08-29
  • 2021-08-02
  • 2021-10-19
  • 2022-12-23
  • 2021-08-28
相关资源
相似解决方案