为运行时创建的对象赋值(python)

2024-10-03 15:23:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用while循环来创建对象,以填充用户定义类型的列表,直到满足某个条件为止。我想根据循环完成的迭代次数为每个对象指定一个值。例如:

class WalkingPeeps:

def___init___(self):
     self.location = 0

def leftAt(self,time):
     self.tleft = time

def changePos(self):
     self.location += random.choice([1, -1])

objectList =[] 
location_reached = False
time = 0

 while not location_reached
      objectList.append(WalkingPeeps())
      for x in objectList:
           x.tleft = time
           if x.location == 20:
                location_reached = True
      time+=1

print("Person left at: ",x.tleft)
print("Person arrived at: ", time)

但是,当它运行时,它只是将对象创建的时间设置为比用户达到20时少一个。有指针吗?提示?提前谢谢


Tags: 对象用户selftimedeflocationatperson
1条回答
网友
1楼 · 发布于 2024-10-03 15:23:29

在python中,循环并不定义自己的作用域。当你写作的时候

for x in objectList: ...

创建了变量x。在循环的每个步骤中,变量都会更新。循环结束时,变量未被销毁。因此,当您打印x.tleft时,您是在最后一个x上打印时间,根据定义是20,因为只有当x.tleft==20时才会中断循环

此外,由于在每个阶段循环每个元素并更新其时间,因此将每个元素的时间设置为最新时间。因此,当终止时,所有元素的时间==20。我相信,你的意思是只更新最后一个元素

我想你要打印的,检查你的循环是否正常

for obj in objectList:
    print( obj.tleft )

然后你就会看到预期的行为

您也有许多错误,包括一些语法错误和一些使代码进入无限循环的错误。这是我真诚地使用的版本(试着确保代码中唯一的bug就是你要问的那个!)

class WalkingPeeps: pass # None of the methods were relevant

objectList =[]
location_reached = False
time =0

while not location_reached:
    objectList.append(WalkingPeeps())
    x = objectList[-1]
    x.tleft = time
    # you need to check tleft, not location; location is never set
    if x.tleft == 20: 
    location_reached = True
    time+=1


print("Person left at: ",x.tleft)
print("Person arrived at: ", time)
for person in objectList: print(person.tleft)

这段代码的一个更具可读性和简洁性的版本是:

class WalkingPerson:
       def __init__(self,time=0):
              self.time=time

objectList = [WalkingPerson(t) for t in range(20)]

相关问题 更多 >