今天看到一段代码,其中函数入参有一个参数为list,类似如下:

def linux_monitor(pid=0,pidlist = []):
    pidlist.append(pid)

 

 

通过测试发现是有问题的,在其中加入print和调用即可发现(使用默认参数值调用俩次):

def linux_monitor(pid=0,pidlist = []):
    pidlist.append(pid)
    print(pid)
    print(pidlist)

linux_monitor()
linux_monitor()

 

 

结果如下:

python之函数参数问题(参数为可变对象)

 

第二次调用的时候,pidlist并不是空的

 

所以对于可变参数,特别需要注意,如列表等都可能产生这样的问题

 

我们可以对代码做如下处理即可正常使用:

def linux_monitor(pid=0,pidlist = None):
  if pidlist == None:
    pidlist = []
  pidlist.append(pid)
  print(pid)
  print(pidlist)

 

 

大家可以试一下

相关文章:

  • 2022-12-23
  • 2021-12-25
  • 2021-08-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
猜你喜欢
  • 2022-12-23
  • 2021-08-04
  • 2022-12-23
  • 2021-09-22
  • 2022-12-23
  • 2021-12-07
相关资源
相似解决方案