首页 > 解决方案 > 如何修复“xcor() 缺少 1 个必需的位置参数:Python 中的‘self’错误

问题描述

我只是想从我创建的海龟类中引用海龟的位置。我觉得我在做的事情在理论上是不正确的,但看起来好像它会起作用。也许这个错误超出了我的范围,但我不确定。

我尝试过其他放置海龟的方法,但它们变得非常复杂且无法使用。

class Maze_wall(Turtle):

    def __init__(self, x_loc, y_loc):
       super().__init__()
       self.color("#ffffff")
       self.penup()
       self.speed(0)
       self.shape("square")
       self.shapesize(stretch_wid=0.95, stretch_len=0.95)
       self.goto(x_loc, y_loc)
       self.showturtle()

上面是我的海龟类,下面我尝试引用海龟的 x 和 y 坐标。

def wall_right():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())
def wall_left():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())
def wall_up():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())
def wall_down():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())

我的目标是让每个函数根据海龟的当前位置放置一个海龟。

标签: pythonclassturtle-graphicssuperclass

解决方案


简短的回答:您正在调用.xcor()海龟子类而不是海龟实例。

更长的答案:您似乎将用于布置迷宫的乌龟与将成为迷宫墙壁的乌龟混为一谈。你不能在墙存在之前问它的位置。我所期望的是代码更像:

from turtle import Screen, Turtle

class Maze_wall(Turtle):

    def __init__(self, x_loc, y_loc):
        super().__init__(visible=False)

        self.shape('square')
        self.speed('fastest')
        self.color('black')
        self.penup()
        self.shapesize(stretch_wid=0.95, stretch_len=0.95)
        self.goto(x_loc, y_loc)
        self.showturtle()

def wall_right(turtle):
        return Maze_wall(turtle.xcor(), turtle.ycor())

builder = Turtle(visible=False)
builder.penup()

walls = []

for _ in range(4):
    builder.forward(100)
    wall = wall_right(builder)
    walls.append(wall)
    builder.left(90)

screen = Screen()
screen.exitonclick()

推荐阅读