2

Can someone please explain me the following code TickGenerator inherit from object and methods of Observer, why do we need both observer.init?

class TickGenerator(Observer):
    def __init__(self):
        Observer.__init__(self)
        self.price = 1000
Ben
  • 51,770
  • 36
  • 127
  • 149
matel
  • 425
  • 5
  • 12

3 Answers3

5

I guess you came from a language where the parent class constructor is automatically called.

In Python, if you override the __init__ method, the parent class constructor will not be called unless you call it explicitly.

Until Python 3, it used to be called as:

def __init__(self, *args, **kwargs):
    super(TickGenerator, self).__init__(*args, **kwargs) 

The new [super()][1] syntax (PEP-3135) is just:

def __init__(self, *args, **kwargs):
    super().method(*args, **kwargs)
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
  • `Observer.__init__(self)` isn't it a calling to the super class constructor ? – 0x90 Apr 06 '13 at 12:36
  • 1
    I guess the OP question is why he has to call `Observer.__init__(self)` at all, and it makes sense if he is versed in a computer language where the parent constructor call is implicit. – Paulo Scardine Apr 06 '13 at 12:38
3

Because programmer needs Observer class __init__ to be done in addition to what is being done in the current class's (TickGenerator) __init__.

This Stackoverflow answer will help you understand more.

Community
  • 1
  • 1
Rahul Gautam
  • 4,749
  • 2
  • 21
  • 30
1

If you don't call Observer.init as below:

class TickGenerator(Observer):
    def __init__(self):
        self.price = 1000

It means you override the TickGenerator.init method and Observer.init will not be called automaticlly.

Yarkee
  • 9,086
  • 5
  • 28
  • 29