Search code examples
pythonfunctionclassrectangles

How could i call a object from the class point so that i can use it in rectangle


I wanted to call the x and y point from a the class point and implement it in the class rectangle so that i would input x,y,w,h and it would print a point(x,y) with a certain height and width and also print an area.

an example of what it is supposed to produce is

Rectangle at(3,2) with height = 2 width = 1 , area = 2

however, I kept getting this error on line 22:

 __str__
    result += str(self._X)+ ',' + str(self._Y) + ')'
AttributeError: 'rectangle' object has no attribute '_X'

This the current code I had:

import math
import sys
import stdio

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

class rectangle:
     def __init__(self,x,y, w, h):
        self._h = h
        self._w = w

     def area(self):
          a = self._h * self._w
          return a

     def __str__(self):
          result = 'Rectangle at('
          result += str(self._X)+ ',' + str(self._Y) + ')'
          result += ' with height = ' + str(self._h)
          result += ' width = ' + str(self._w)
          result += ' , area = ' + str(self.area())
          return result


def main():
     x = int(input(sys.argv[0]))
     y = int(input(sys.argv[0]))
     w = int(input(sys.argv[0]))
     h = int(input(sys.argv[0]))
     
     rect = rectangle(x,y,w,h)
     stdio.writeln(rect)

     
if __name__ == '__main__':
     main()




Solution

  • I think you meant to create a Point in your rectangle:

    class rectangle:
         def __init__(self,x,y, w, h):
            self.point = Point(x, y)
            self._h = h
            self._w = w
    
         def area(self):
              a = self._h * self._w
              return a
    
         def __str__(self):
              result = 'Rectangle at('
              result += str(self.point._X)+ ',' + str(self.point._Y) + ')'
              result += ' with height = ' + str(self._h)
              result += ' width = ' + str(self._w)
              result += ' , area = ' + str(self.area())
              return result