在 python 的 init 方法中更改属性



所以在我的snake类中,我初始化了一个属性self.x_cor = 0现在,我想在不同的方法(create_segment)中修改或使用此属性。只有当我再次重复(create_segment)中的代码行(self.x_cor = 0)时,它才有效。

如果我不重复它,我会得到反馈,说蛇对象没有属性x_cor同时我在 init 方法中初始化了它

如何使用其他方法来修改在 init 方法中初始化的属性?

import turtle
from turtle import Turtle
import random
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0

class Snake:
def __init__(self):
self.speed = 9
self.segments = []
self.create_snake()
self.x_cor = 0
self.y_cor = 0
# self.add_segment()
self.head = self.segments[0]  # the first segment is designated as the head of the snake
self.color_list = [(202, 164, 110), (240, 245, 241), (236, 239, 243), (149, 75, 50), (222, 201, 136),
(170, 154, 41), (138, 31, 20), (134, 163, 184), (197, 92, 73), (47, 121, 86), (73, 43, 35),
(145, 178, 149), (14, 98, 70), (232, 176, 165), (160, 142, 158), (54, 45, 50), (101, 75, 77),
(183, 205, 171), (36, 60, 74), (19, 86, 89), (82, 148, 129), (147, 17, 19), (27, 68, 102),
(12, 70, 64), (107, 127, 153), (176, 192, 208), (168, 99, 102), (53, 93, 123)]
self.colors = ["red", "orange", "yellow", "blue", "green", "purple"]
def create_snake(self):
""" Creates the snake """
for n in range(3):  # Creates 3 segments for now
self.create_segment(n)
def create_segment(self, n):
""" Creates a new segment to be added to the snake """
new_segment = Turtle("square")
turtle.colormode(255)
self.color_list = [(202, 164, 110), (240, 245, 241), (236, 239, 243), (149, 75, 50), (222, 201, 136),
(170, 154, 41), (138, 31, 20), (134, 163, 184), (197, 92, 73), (47, 121, 86), (73, 43, 35),
(145, 178, 149), (14, 98, 70), (232, 176, 165), (160, 142, 158), (54, 45, 50), (101, 75, 77),
(183, 205, 171), (36, 60, 74), (19, 86, 89), (82, 148, 129), (147, 17, 19), (27, 68, 102),
(12, 70, 64), (107, 127, 153), (176, 192, 208), (168, 99, 102), (53, 93, 123)]
# new_segment.color(random.choice(self.color_list))
self.colors = ["red", "orange", "yellow", "blue", "green", "purple"]
new_segment.color(random.choice(self.colors))
new_segment.penup()
# new_segment.speed(9)
self.x_cor = 0
self.y_cor = 0
new_segment.goto(self.x_cor, self.y_cor)
self.x_cor -= 20  # Reduce the x_cor but maintain the y so all the segments will be on the same horizontal
# but different vertical axis
self.segments.append(new_segment)

如果我不重复

self.x_cor = 0
self.y_cor = 0

在第二种方法中,我得到的反馈为"第 49 行,create_segment new_segment.goto(self.x_cor, self.y_cor) 属性错误:"蛇"对象没有属性"x_cor"。你的意思是:"y_cor"?

我真的认为重复是不必要的,但我如何避免这种情况? 谢谢

在构造函数的create_snake中,您基本上是在尝试在创建self.x_cor之前访问它,因为create_snake调用create_segment在初始化之前引用self.x_cor

最新更新