Help with Python polymorphism

Help me understand the code. I can not understand its principle of operation.

class Base:

     def __init__(self,N):
          self.numb = N

     def out(self):
         self.numb /= 2 
         print (self.numb)

class Subclass(Base):

     def out(self):
          print ("----")
          Base.out(self)
          print ("----")

i = 0

while i < 10:
     if 4 < i < 7:
          obj = Subclass(i)
     else:
          obj = Base(i)
     i += 1
     obj.out()

0
0
1
1
2
----
2
----
----
3
----
3
4
4

What is the principle of print output? why only up to 4 outputs?

Author: jfs, 2015-07-21

2 answers

Well, look: we have two classes that have a similar interface, in this case, the out method. Polymorphism is that we can interact with different classes through a single interface. If the Base class in the out method simply outputs numb/2, then Subclass will output the same thing framed by signs ---- Polymorphism allows us to interact with objects of both classes in a single loop, and each of them behaves differently.

Everything is simple here, but here is an example probably not vital, that's why it's not clear. Here is an example of the application of polymorphism from life: for example, we need to draw geometric shapes. We have an abstract Shape class with the draw method:

class Shape(object):
    def draw(self):
        print 'рисую фигуру'

And the Triangle and Square classes, inheritors of the Shape class:

class Triangle(Shape):
    def draw(self):
        print 'рисую треугольник'

class Square(Shape):
    def draw(self):
        print 'рисую квадрат'

Now, if we have an array of geometric shapes, we can handle it the same way, regardless of the shape, and each of the classes will draw its own shape in its own way.

 4
Author: Алексей Стародубцев, 2015-07-21 14:10:02

What kind of behavior did you expect? All correct 9 times output. Of these, 2 are from Subclass. 9/2 == 4 because the whole-number division. Replace i = 0 with i = 0.0 and everything will be clear.

 0
Author: VladimirAbramov, 2015-07-21 18:17:42