1

我有以下代码。代码的最后一个功能应该将孩子聚集到他们的母亲那里。

class MotherTurtle(Turtle):  
    def __init__(self, home):
        Turtle.__init__(self, home)
        self.children = []
        self.home = home
        self.setName("Mum")
        
    def giveBirth(self, name):
        newborn = Turtle(self.home)
        newborn.setName (name)
        self.children.append(newborn)
        return newborn
        
    def greetChildren(self):
        for child in self.children:
            print "Hi %s" %(child.name)
                
    def gatherChildren(self):
        for child in self.children:
            child.moveTo(self.home)

我需要把孩子们聚集到他们的母亲那里。

在此处输入图像描述

这是我运行程序时遇到的错误:

======= Loading Progam =======
>>> world = makeWorld()
>>> mum = MotherTurtle(world)
>>> mary = mum.giveBirth("Mary")
>>> jimmy = mum.giveBirth("Jimmy")
>>> mum.greetChildren()
Hi Mary
Hi Jimmy
>>> mary.turn(-45)
>>> mary.forward(120)
>>> jimmy.turn(90)
>>> jimmy.forward()
>>> mum.gatherChildren()

错误是:

'list' 对象没有属性 'moveTo' 找不到属性。您正在尝试访问不存在的对象的一部分。请检查 C:\Users\user\Desktop\159171 的第 21 行

4

1 回答 1

0

方法如下:

def gatherChildren(self):
    
    # get the position of the mother turtle    
    mumX = self.getXPos()
    mumY = self.getYPos()
    # use an offset so not all turtles are on top of each other
    spacing = 10
    offset = spacing
    # loop through the list of children to place each child close to the mother
    for child in self.children:
      child.moveTo(mumX + offset, mumY + offset)
      offset = offset + spacing
于 2012-05-28T12:46:36.297 回答