在Python中初始化超类

时间:2013-03-22 22:30:04

标签: python class inheritance initialization

我正在学习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)

错误无限期重复。<​​/ p>

以下是使用合成语言执行我想要的代码:

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()

2 个答案:

答案 0 :(得分:0)

python 2.7的简单代码是:

BaseClassName.__init__(self, args)

答案 1 :(得分: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