1

我正在学习 Python。目前,我可以通过组合做我想做的事情,但是当我尝试使用继承做同样的事情时,我得到一个错误。这是我的代码。我基本上是在尝试为彩色方块开设课程。

from graphics import *

class Block(Rectangle):
    def __init__(self, corner, colour):
        self.corner = corner
        self.colour = colour
        self.x1 = self.corner.getX() * 30
        self.y1 = self.corner.getY() * 30
        self.x2 = self.x1 + 30
        self.y2 = self.y1 + 30
        self.point1 = Point(self.x1, self.y1)
        self.point2 = Point(self.x2, self. y2)
        Rectangle.__init__(self, self.point1, self.point2)


    def draw(self, window):
        self.window = window
        self.Rectangle.draw(self.window)


new_win = GraphWin("thingy", 700, 500)
corner = Point(1, 1)
square1 = Block(corner, 'red')
square1.draw(new_win)

new_win.mainloop()

我得到的错误是

File "F:\Python\4\4_3.py", line 24, in draw
self.draw(self.window)

错误无限重复。

这是我在使用组合时执行我想要的代码:

from graphics import *

class Block():
    def __init__(self, corner, colour):
        self.corner = corner
        self.colour = colour
        self.x1 = self.corner.getX() * 30
        self.y1 = self.corner.getY() * 30
        self.x2 = self.x1 + 30
        self.y2 = self.y1 + 30
        self.point1 = Point(self.x1, self.y1)
        self.point2 = Point(self.x2, self. y2)
        self.Rectangle = Rectangle(self.point1, self.point2)

    def draw(self, window):
        self.window = window
        self.Rectangle.draw(self.window)
        self.Rectangle.setFill(self.colour)


new_win = GraphWin("thingy", 150, 150)
corner = Point(1, 1)
square1 = Block(corner, 'red')
square1.draw(new_win)

new_win.mainloop()
4

2 回答 2

0

python 2.7的简单代码是:

BaseClassName.__init__(self, args)

于 2013-03-22T22:47:47.313 回答
0
from graphics import *

class Block(Rectangle):
    def __init__(self, corner, colour):
        self.corner = corner
        self.colour = colour
        self.x1 = self.corner.getX() * 30
        self.y1 = self.corner.getY() * 30
        self.x2 = self.x1 + 30
        self.y2 = self.y1 + 30
        self.point1 = Point(self.x1, self.y1)
        self.point2 = Point(self.x2, self. y2)

        Rectangle.__init__(self, self.point1, self.point2)


    def draw(self, window):
        self.window = window
        Rectangle.draw(self, self.window)
        # instead of self.Rectangle.draw(self.window)

在继承的情况下,没有self.Rectangle

于 2013-03-22T22:59:40.460 回答