Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python basic explanation needed

Tags:

python

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
like image 460
matel Avatar asked Sep 27 '26 15:09

matel


2 Answers

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)
like image 68
Paulo Scardine Avatar answered Sep 30 '26 05:09

Paulo Scardine


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.

like image 36
Rahul Gautam Avatar answered Sep 30 '26 05:09

Rahul Gautam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!