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
3 Answers 3
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)
2 Comments
Observer.__init__(self) isn't it a calling to the super class constructor ?Observer.__init__(self) at all, and it makes sense if he is versed in a computer language where the parent constructor call is implicit.Because programmer needs Observer class __init__ to be done in addition to
what is being done in the current class's (TickGenerator) __init__.
Comments
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.
super()builtin.