[英]How to get the name of the module, calling a specific function, in Python.
[英]Python. Calling a function that applies a mutation to an object. Mutation does not apply in the calling context
我有一个 class,它有一个名为 tour 的字段。 在那个 class 中,我还有一个 function 可以从旅行中删除一个位置。
def remove(self,location, to_print=False):
location.tour_id = None
index_to_delete = None
if to_print:
print("before removee" +str(len(self.tour_locations)))
for i in range(0,len(self.tour_locations)):
if self.tour_locations[i].id_ == location.id_:
index_to_delete = i
if index_to_delete is None:
print("element not found")
return
else:
del self.tour_locations[index_to_delete]
if to_print:
print("after removee" +str(len(self.tour_locations)))
现在我从其他地方调用这个 function(不在 TOUR CLASS 中):
def apply(self):
tour_location = self.extra_information['tour_location']
position = self.extra_information['position']
tour= self.extra_information['tour']
origin_tour = self.solution.get_tour_by_id(tour_location.tour_id)
destination_tour = self.solution.get_tour_by_id(tour.id_)
if to_print:
print("origin_tour before " + str(origin_tour))
print("dstination tour before" + str(destination_tour))
origin_tour.remove(tour_location, to_print=to_print)
destination_tour.insert_at(tour_location, position)
if to_print:
print("origin_tour after " + str(origin_tour))
print("dstination tour after" + str(destination_tour))
return self.solution
class 中的打印行正在打印与位置删除一致的游览。
应用 function 中的打印行(“之后”)显示没有任何修改的游览。
这是怎么回事?
您不应该使用del
从列表中删除项目。 请改用list.pop(index)
或list.remove(value)
。 在您的情况下,您应该使用list.pop(index)
因为您想从列表中删除特定索引处的项目。 文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.