【问题标题】:Is there a way to make turtle-graphics object oriented?有没有办法使海龟图形面向对象?
【发布时间】:2021-07-13 10:13:27
【问题描述】:
class Paddle(turtle.Turtle):
    def __init__(self, pos, color, shape, speed, shape_size):
        self.turtle.pos = turtle.goto(pos)
        self.turtle.color = turtle.color(color)
        self.turtle.shape = turtle.shape(shape)
        self.turtle.speed = turtle.speed(speed)
        self.turtle.shapesize = turtle.shapesize(shapesize)

OOP Python 海龟模块 我试图通过尝试上面的代码块来使我的游戏面向对象,但我得到 AttributeError: 'Paddle' object has no attribute 'turtle' 回溯。老实说,我从来没有用继承和模块组合做过面向对象编程,所以我不太确定我应该做什么。如果您有资源可以让我了解继承如何与模块一起使用,我将不胜感激!

【问题讨论】:

    标签: python oop module turtle-graphics


    【解决方案1】:

    Python 海龟图形是面向对象的。问题是,“有没有办法让你的程序面向对象?”我们可以以面向对象的方式实现您的代码尝试做的事情的精神,例如:

    from turtle import Screen, Turtle
    
    class Paddle(Turtle):
        def __init__(self, position, color, shape, speed, stretch):
            super().__init__(shape=shape, visible=False)
    
            self.penup()
            self.goto(position)
            self.color(color)
            self.shape(shape)
            self.speed(speed)
            self.shapesize(stretch, 1)
    
            self.showturtle()
    
    screen = Screen()
    
    paddle1 = Paddle((100, 100), 'blue', 'square', 'fastest', 3)
    paddle2 = Paddle((-100, 100), 'red', 'square', 'fastest', 3)
    
    screen.exitonclick()
    

    您混合了 isa 和 contains 的 OOP 概念。上述解决方案只使用 isa

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 2011-11-05
      • 2022-01-22
      • 2018-05-30
      • 2019-04-23
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多