External Exam Download Resources Web Applications Games Recycle Bin

Polymorphic override, and private member variable

polymorphic and private.py

class Shape: #super class
  def __init__(self, length=0):
    self.__length = length #__double underscore DENY access outside of class
  def area(self):
    return "Shape does not have area"
  def getLength(self): #have to implement this method to access length
    return self.__length

class Rectangle(Shape): #sub class
  def __init__(self, length=0, width=0):
    super(Rectangle, self).__init__(length) #init the parent class __length
    self.width = width
  def area(self):  #override area method - area is polymorphic
    return self.width * self.getLength() #cant access directly as private

line = Shape(10)
print( line.area() ) #Shape does not have area
box = Rectangle(3,4)
print( box.area() ) #12, calculates by access private variable __length