Python Generalisation/Polymorphism - invoking superclass method having subclass object in print()

37 views Asked by At

It is academic problem that I present here. The case is to invoke __str__() method of superclass having object of subclass. The case is presented in last two lines (marked with comment hashes. In line commented as #1 you will see what I was expecting (or I wish it should work). Comment line #2 shows what I need to do to get expected result.

  • My question is why expression like: subclassObject.base() - that should downgrade the object and return superclass - placed in print() function does not itself use superclass __str__() method like I do expect, instead returning object description?
  • What to do (what I need to define in any of those classes), so that print() method receiving downgraded object of subclass (to more general object) would by default use superclass method __str__()?

Code:

class Orto():
   "General class"
   def __init__(self):
       "Initialise"
       print("Nothing, just init", end=" ")

   def __str__(self):
       "To string"
       return "To string"

   def length(self, _a, _b, _c, _d):
       "Count"
       return _a + _b + _c + _d


class Rectangle(Orto):
   "Rectangle case"
   def __init__(self):
       super().__init__()
       print("... and an rectangle")

   def base(self):
       return super()

   def __str__(self):
       return super().__str__() + " rectangle"

   def length(self, _a, _b):
       return super().length(_a, _b, _a, _b)


o = Orto()
print(o, " ", o.length(2, 4, 2, 4))
#OUTPUT: Nothing, just init To string   12

r = Rectangle()
print(r, " ", r.length(3, 5))
#OUTPUT: Nothing, just init ... and an rectangle
#        To string rectangle   16

c = r.base()
print(c, " ", r.base().length(5, 5, 8, 5)) #1
#OUTPUT: <super: <class 'Rectangle'>, <Rectangle object>>   23 <------ got this
#EXPECTED: To string   23   <------ expected that

print(c.__str__(), " ", r.base().length(5, 5, 8, 5)) #2
#OUTPUT: To string   23   <------  need explicit use of __str__() to get expected result
0

There are 0 answers