我有函数声明,如:
def function(list_of_objects = None)
如果 *list_of_objects* 没有通过(没有),我需要将它定义为空列表。明确的方式是:
def function(list_of_objects = None):
if not list_of_objects:
list_of_objects = list()
或者
def function(list_of_objects = None):
list_of_objects = list() if not list_of_objects else list_of_objects
上面的代码是否等于下一个?
def function(list_of_objects = None):
list_of_objects = list_of_objects or list()
我测试了它,但我仍然不确定
>>> def func(my_list = None):
... my_list = my_list or list()
... print(type(my_list), my_list)
...
>>> func()
(<type 'list'>, [])
>>> func(['hello', 'world'])
(<type 'list'>, ['hello', 'world'])
>>> func(None)
(<type 'list'>, [])
>>>