Anthony Do
Anthony Do

Reputation: 1419

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.

Upvotes: 0

Views: 3682

Answers (2)

hjpotter92
hjpotter92

Reputation: 80629

class Rectangle(object):
  def __init__(self, pos, width, height):
    self._x = pos[0]
    self._y = pos[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

The code is running here: http://codepad.org/VfqMfXrt

Upvotes: 1

Kris Harper
Kris Harper

Reputation: 5862

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

Upvotes: 4

Related Questions