问题描述
我正在尝试从海龟构建蛇,但在使用海龟类中的 .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'
如果有人知道发生了什么,请帮忙,谢谢!
解决方法
您在调用 super().__init__()
时正在调用超类的构造函数。
如果你想调用 super 的方法,就做
xcor = super().xcor()
ycor = super().ycor()
,
super().__init__
是类 Turtle
的初始化方法。它没有 xcor
或 ycor
属性。我认为您打算在您创建的分段上调用 x|y cor
方法,这要简单得多:
segment = super().__init__(shape="square")
self.xcors.append(segment.xcor())
self.ycors.append(segment.ycor())
您可能会更轻松:
self.segments = [super().__init__(shape="square") for _ in range(4)]
然后遍历这些段以设置每个段的所需特征:
self.color("black")
for square in self.segments:
# draw each segment in turn