【问题标题】:I want to create mutiple turtles in newly created class我想在新创建的类中创建多个海龟
【发布时间】:2019-10-16 03:45:12
【问题描述】:

我遇到了一个问题,我必须创建一个简单的面向对象的代码来创建两个朝相反方向移动的海龟,但在我的试验中我遇到了未知错误

我尝试用self 初始化两个变量turtle1turtle2,因为我继承了Turtle 和s

from turtle import *
class moveOpposite(Turtle):
    def __init__(self):
        self.setx=0
        self.sety=0
    def move(self):
        turtle1=self
        turtle2=self
        turtle1.forward(100)
        turtle2.forward(-100)


my_turtle=moveOpposite()
my_turtle.move()

我没有使用self._go,但我的错误提示我这样做了:

self._go(distance)

我也没有使用self._position 等,但它也说我使用了并给了我一个AttributeError

ende = self._position + self._orient * distance
AttributeError: 'moveOpposite' object has no attribute '_position'

【问题讨论】:

  • turtle1=selfturtle2=self 之后,您现在只需为单个海龟对象设置三个名称——实际上您还没有创建 任何东西。而且您的moveOpposite 类的实例无论如何都不是有效的Turtles,因为您的__init__() 不会调用继承的__init__(),它会执行各种必要的初始化。

标签: python class turtle-graphics


【解决方案1】:

我不会从 Turtle 继承,即 isa,在这种情况下,因为您的对象不是乌龟而是一对。我会改用 contains 方法:

from turtle import Screen, Turtle

class Zax():  # a la Dr. Suess
    def __init__(self):
        self.east_bound = Turtle('turtle')
        self.west_bound = Turtle('turtle')
        self.west_bound.setheading(180)

    def forward(self, distance):
        self.east_bound.forward(distance)
        self.west_bound.forward(distance)

    def right(self, angle):
        self.east_bound.right(angle)
        self.west_bound.right(angle)

    def left(self, angle):
        self.east_bound.left(angle)
        self.west_bound.left(angle)

screen = Screen()

zaxen = Zax()
zaxen.forward(100)

for _ in range(4):
    zaxen.forward(20)
    zaxen.right(90)

screen.exitonclick()

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多