我的作业需要在两个类(人和世界)中编写函数,我很确定我的代码是正确的。然而,
“AttributeError:'世界'对象没有属性'目的地'”
当self.destination仅存在于Person类中时,它会一直显示。
似乎“自我”这个词现在指的是世界级,我无法弄清楚为什么。
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'
**
列表self.people
上有Person,所以你应该循环使用这个列表
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()
或类似的东西。