首页 > 解决方案 > 在 Python 中使用 Turtles 时出现属性错误

问题描述

我正在尝试从海龟构建蛇,但在使用海龟类中的 .xcor()、.ycor()、.pos() 函数时遇到属性错误。基本上任何从海龟类返回值的东西在我的程序中都不起作用。这是我的代码:

from turtle import Turtle, Screen
import time 
import random
screen = Screen()


class Snake(Turtle) : ## create snake class and pass Turtle class into it 

    def __init__(self):
        self.xcors = []
        self.ycors = []
        self.snakesegs = []
        self.create_snake()

    def create_snake(self):   
        N = 0
        for segs in range(1,4):
            super().__init__(shape="square")
            self.color("black")
            self.penup()
            self.goto(N,0)
            self.snakesegs.append(super().__init__)
            N -= 20
            xcor = super().__init__.xcor()
            ycor = super().__init__.ycor()
            self.xcors.append(xcor)
            self.ycors.append(ycor)

这是我得到的回溯:

Traceback (most recent call last):
  File "/Users/gcinco/Documents/Python/Jett-Black/SNAKE/snake.py", line 49, in <module>
    snape = Snake()
  File "/Users/gcinco/Documents/Python/Jett-Black/SNAKE/snake.py", line 13, in __init__
    self.create_snake()
  File "/Users/gcinco/Documents/Python/Jett-Black/SNAKE/snake.py", line 24, in create_snake
    xcor = super().__init__.xcor()
AttributeError: 'function' object has no attribute 'xcor'

如果有人知道发生了什么,请帮忙,谢谢!

标签: pythonclassattributesturtle-graphicspython-turtle

解决方案


调用时,您正在调用超类的构造函数super().__init__()。如果你想调用 super 的方法,就做

xcor = super().xcor()
ycor = super().ycor()

推荐阅读