-2

I created two super classes Polygon and Shape. I created a sub class Rectangle to inherit properties of both of these classes. Rectangle class object can access attributes from Polygon class, but not from Shape class. Please help

This for python 3. I tried by removing 'Shape' Class, it worked fine. It is not inheriting Shape class

Polygon.py

class Polygon:
    __width = None
    __height = None

    def setvalues(self, height, width):
        self.__height = height
        self.__width = width

    def getheight(self):
        return self.__height

    def getwidth(self):
        return self.__width

Shape.py

class Shape:
    __colour = None

def set_colour(self, colour):
    self.__colour = colour

def get_colour(self):
    return self.__colour

rectangle.py

from polygon import Polygon
from shape import Shape

class Rectangle(Polygon, Shape):
    def GetRectArea(self, height, width):
        Obj1 = Polygon()
        Obj1.setvalues(height, width)
        return Obj1.getheight() * Obj1.getwidth()

    def GetRecttcolour(self):
        Obj1 = Shape()
        Obj1.set_colour('Red')
        return self.get_colour()

main.py

from rectangle import Rectangle 

rect1 = Rectangle()
tri1 = Triangle()

print(rect1.GetRectArea(10, 20))
print(rect1.GetRecttcolour()())

I expect the output of

200  
'Red'

But I get :

200  
Traceback (most recent call last):
  File "G:\Python\Workspace\Python OOP concepts\MultipleInheritnce.py", line 11, in <module>
    print(rect1.GetRecttcolour()())
  File "G:\Python\Workspace\Python OOP concepts\rectangle.py", line 21, in GetRecttcolour
    Obj1.set_colour('Red')
AttributeError: 'Shape' object has no attribute 'set_colour'
dejanualex
  • 3,872
  • 6
  • 22
  • 37
Sateesh
  • 21
  • 7

1 Answers1

0

Do the same like in GetRectArea method:

class Rectangle(Polygon, Shape):

  def GetRectArea(self, height, width):
      Obj1 = Polygon()
      Obj1.setvalues(height, width)
      return Obj1.getheight() * Obj1.getwidth()

  def GetRecttcolour(self):
      Obj1 = Shape()
      Obj1.set_colour('Red')
      return Obj1.get_colour()

And when calling the method GetRecttcolour, it will give you the desired output '200' and 'Red':

rect1 = Rectangle()

print(rect1.GetRectArea(10, 20))
print(rect1.GetRecttcolour())

But if you want to use getters and setter you have the property decorator, here you can find a good explanation on how they work: How does the @property decorator work?.

Also if you want to see the MRO (hierarchy in which base classes are searched when looking for a method in the parent class), use the built-in function help(Rectangle) and you will get lots of useful information:

enter image description here

dejanualex
  • 3,872
  • 6
  • 22
  • 37