pythonclassself

Defining a class in python in python


class Rectangle(object):

def __init__(self, (top left corner), width, height):
    """
    __init__(self, (x, y), integer, integer)
    """

    self._x = x
    self._y = y
    self._width = width
    self._height = height

def get_bottom_right(self):
    x + self.width = d
    y + self.height = t

return '' + d,t

so i am trying to make a class for a rectangle, i am trying to find the bottom right of the rectangle. the bottom right of the rectangle can be found by adding the height and width onto the top left corner. eg. (2,3),4,7 would make the bottom corner be (6,10). however, i dont believe my code is right. this is my first time using classes so some hints and tricks on how to interpret this would be very helpful.


Solution

  • I think what you want is this

    class Rectangle(object):
      def __init__(self, top_corner, width, height):
        self._x = top_corner[0]
        self._y = top_corner[1]
        self._width = width
        self._height = height
    
      def get_bottom_right(self):
        d = self._x + self.width
        t = self._y + self.height
        return (d,t)
    

    You can use this like this

    # Makes a rectangle at (2, 4) with width
    # 6 and height 10
    rect = new Rectangle((2, 4), 6, 10) 
    
    # Returns (8, 14)
    bottom_right = rect.get_bottom_right
    

    Also, you could probably save yourself some time by making a Point class

    class Point(object):
        def __init__(self, x, y):
            self.x = x
            self.y = y