从子类中具有不同名称的父类调用方法

2024-04-24 10:48:13 发布

您现在位置:Python中文网/ 问答频道 /正文

具有以下代码:

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

我想通过从类Point调用self\u rep\uuuu(self)来打印“Point(0,0)”,方法是get\u bottom\u left,但我不知道如何打印。如果函数具有相同的名称,我知道如何使用继承,但在这种情况下,我陷入了困境,要求子函数具有它所具有的方法名称。如果看起来我只是在寻找答案,我想回答只是解释我一个类似的情况下,这个应用请

当我执行以下操作时:

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)

I get:get\u bottom\u left()缺少1个必需的位置参数:“bottom\u left”


Tags: selfrightnonenumbergettopdefleft
1条回答
网友
1楼 · 发布于 2024-04-24 10:48:13

如注释中所述,矩形应该包含点实例,而不是继承点。如果按如下所示更改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

相关问题 更多 >