Python - 添加功能以访问上次调用的信息
Python - add functionality to function to access information from previous call
我得到了如下函数:
def my_func(some_objects):
objects_information = []
for object_ in some_objects:
object_information = dict()
object_information['name'] = some_object.name
object_information['position'] = some_object.position
object_information['previous_position'] = previous_position or None
objects_information.append(object_information)
return objects_information
如何向该函数添加一个选项来保存有关对象位置的信息,以便在 object_information['previous_position']
行中我可以使用上次调用该函数的信息 object_position['position']
?如果 object_information['name']
与之前的调用相同,并且如果它是第一个使用 object_name 的调用,它将把 None 放在 previous_position 键中。
非常感谢
functionality to function to access information from previous call
要获得此类功能,您可以利用 mutable default argument gotcha,请考虑以下示例
def remember(arg, seen=[]):
seen.append(arg)
return seen
print(remember(3))
print(remember(5))
print(remember(7))
输出
[3]
[3, 5]
[3, 5, 7]
请注意,这通常是 python
编码人员不知道此行为的陷阱,因此如果您决定使用它,请将其记录下来。
我得到了如下函数:
def my_func(some_objects):
objects_information = []
for object_ in some_objects:
object_information = dict()
object_information['name'] = some_object.name
object_information['position'] = some_object.position
object_information['previous_position'] = previous_position or None
objects_information.append(object_information)
return objects_information
如何向该函数添加一个选项来保存有关对象位置的信息,以便在 object_information['previous_position']
行中我可以使用上次调用该函数的信息 object_position['position']
?如果 object_information['name']
与之前的调用相同,并且如果它是第一个使用 object_name 的调用,它将把 None 放在 previous_position 键中。
非常感谢
functionality to function to access information from previous call
要获得此类功能,您可以利用 mutable default argument gotcha,请考虑以下示例
def remember(arg, seen=[]):
seen.append(arg)
return seen
print(remember(3))
print(remember(5))
print(remember(7))
输出
[3]
[3, 5]
[3, 5, 7]
请注意,这通常是 python
编码人员不知道此行为的陷阱,因此如果您决定使用它,请将其记录下来。