Python开发easy忽略的问题

这篇文章主要介绍了Python程序猿代码编写时应该避免的17个“坑”,也能够说成Python程序猿代码编写时应该避免的17个问题,须要的朋友能够參考下

一、不要使用可变对象作为函数默认值

复制代码代码例如以下:
In [1]: def append_to_list(value, def_list=[]):
   ...:         def_list.append(value)
   ...:         return def_list
   ...:

In [2]: my_list = append_to_list(1)

In [3]: my_list
Out[3]: [1]

In [4]: my_other_list = append_to_list(2)

In [5]: my_other_list
Out[5]: [1, 2] # 看到了吧,事实上我们本来仅仅想生成[2] 可是却把第一次执行的效果页带了进来

In [6]: import time

In [7]: def report_arg(my_default=time.time()):
   ...:         print(my_default)
   ...:

In [8]: report_arg() # 第一次运行
1399562371.32

In [9]: time.sleep(2) # 隔了2秒

In [10]: report_arg()
1399562371.32 # 时间居然没有变

原文地址:https://www.cnblogs.com/zhchoutai/p/6791284.html