我想在新创建的类中创建多个海龟

2024-05-17 13:52:04 发布

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

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

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

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'

Tags: selfgomovemydef错误positiondistance
1条回答
网友
1楼 · 发布于 2024-05-17 13:52:04

在这种情况下,我不会从Turtle继承,也就是说,isa,因为你的对象不是一只乌龟,而是一对乌龟。我会选择包含的方法:

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()

enter image description here

相关问题 更多 >