从子类

时间:2015-12-06 03:02:01

标签: python oop

拥有以下代码:

class Point:
    'class that represents a point in the plane'

    def __init__(self, xcoord=0, ycoord=0):
        ''' (Point,number, number) -> None
        initialize point coordinates to (xcoord, ycoord)'''
        self.x = xcoord
        self.y = ycoord

    def setx(self, xcoord):
        ''' (Point,number)->None
        Sets x coordinate of point to xcoord'''
        self.x = xcoord

    def sety(self, ycoord):
        ''' (Point,number)->None
        Sets y coordinate of point to ycoord'''
        self.y = ycoord

    def get(self):
        '''(Point)->tuple
        Returns a tuple with x and y coordinates of the point'''
        return (self.x, self.y)

    def move(self, dx, dy):
        '''(Point,number,number)->None
        changes the x and y coordinates by dx and dy'''
        self.x += dx
        self.y += dy

    def __repr__(self):
        '''(Point)->str
        Returns canonical string representation Point(x, y)'''
        return 'Point('+str(self.x)+','+str(self.y)+')'

class Rectangle(Point):
    def __init__(self,bottom_left,top_right,color):
        self.get = bottom_left 
        self.get = top_right
        self.color = color
    def get_bottom_left(self,bottom_left):
        print ()

r1 = Rectangle(Point(0,0), Point(1,1), "red")
r1.get_bottom_left()

我希望能够通过方法get_bottom_left从类Point调用self__rep __(self)来打印“Point(0,0)”,但我根本不知道如何。我知道如果函数具有相同的名称,如何使用继承,但在这种情况下,我被卡住了,并且子函数需要具有它具有的方法名称。如果它看起来我只是在寻找答案,我希望回复只是解释一下这个应用程序的类似情况!

当我执行以下操作时:

class Rectangle(Point):
    def __init__(self,bottom_left,top_right,color):
        self.get = bottom_left 
        self.get = top_right
        self.color = color
    def get_bottom_left(self,bottom_left):
        print (self.bottom_left)

我得到:get_bottom_left()缺少1个必需的位置参数:'bottom_left'

1 个答案:

答案 0 :(得分:0)

如注释中所述,Rectangle应该包含Point实例而不是继承Point。如果您更改Rectangle类,如下所示,您将看到预期的结果:

class Rectangle():
    def __init__(self, bottom_left, top_right, color):
        self.bottom_left = bottom_left 
        self.top_right = top_right
        self.color = color

    def get_bottom_left(self):
        print self.bottom_left