我的作业需要在两个类(Person和World)中编写函数,而且我很确定我的代码是正确的。但是,
“ AttributeError:“世界”对象没有属性“目的地””
仅在Person类中存在self.destination时出现提示音。
似乎“自我”一词现在指的是世界一流水平,我不知道为什么。
class Person:
def __init__(self, world_size):
self.world_size = world_size
self.radius = 7
self.location = turtle.position()#this cause attribute error
self.destination = self._get_random_location()#and this causes too
#moves person towards the destination
def move(self):
turtle.setheading(turtle.towards(self.destination))
turtle.forward(self.radius/2)
我应该用Person类的其他单词代替“ self”吗?如果是这样,我该怎么办?
class World:
def __init__(self, width, height, n):
self.size = (width, height)
self.hours = 0
self.people = []
self.add_person()
#everything involve of Person class in World class
#add a person to the list
def add_person(self):
person = Person(1)
self.people.append(person)
def simulate(self):
self.hours += 1
Person.update(self)
def draw(self):
p = Person(self)
p.draw()
**
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\ \AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 746, in callit
func(*args)
File "C:\Users\Desktop\VIRUS_PART_A.py", line 261, in __animation_loop
self.tick()
File "C:\Users\Desktop\VIRUS_PART_A.py", line 216, in next_turn
self.world.simulate()
File "C:\Users\Desktop\VIRUS_PART_A.py", line 124, in simulate
Person.update(self)
File "C:\Users\Desktop\VIRUS_PART_A.py", line 71, in update
Person.move(self)
File "C:\Users\Desktop\VIRUS_PART_A.py", line 79, in move
turtle.setheading(turtle.towards(self.destination))
AttributeError: 'World' object has no attribute 'destination'
**
答案 0 :(得分:0)
您在列表self.people
上有“人”,因此您应该循环使用此列表
def simulate(self):
self.hours += 1
for item in self.people:
item.update(self)
def draw(self):
for item in self.people:
item.draw()
可能在Person
中使用Person.move()
,但应使用self.move()
或类似名称。