我正在创建一个学校项目,该项目需要在列表中记录子例程的每次迭代的事件。但是,它会同时添加两个玩家列表。如何阻止这种情况发生?
例如:
class Player:
l = list()
def append_list(self,i):
self.l.append(i)
p1 = Player()
p2 = Player()
for i in range(0,5):
p1.append_list(i)
print(p1.l)
p2.append_list(i)
print(p1.l)
此代码输出:
[0]
[0, 0]
[0, 0, 1]
[0, 0, 1, 1]
[0, 0, 1, 1, 2]
[0, 0, 1, 1, 2, 2]
[0, 0, 1, 1, 2, 2, 3]
[0, 0, 1, 1, 2, 2, 3, 3]
[0, 0, 1, 1, 2, 2, 3, 3, 4]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
但是我需要它来输出:
[0]
[0]
[0, 1]
[0, 1]
[0, 1, 2]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
答案 0 :(得分:2)
使用单独的实例变量而不是共享的 class变量-这样,您的每个播放器实例都有其 own 列表,而不是共享的:
class Player:
def __init__(self):
self.l = [] # create a instance list l
def append_list(self,i):
self.l.append(i)
# other code identical
输出:
[0]
[0]
[0, 1]
[0, 1]
[0, 1, 2]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
更多: