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
53.1k36 gold badges133 silver badges156 bronze badges
asked Apr 6, 2013 at 12:29
1
  • the canonical way to call the parent constructor is using the super() builtin. Commented Apr 6, 2013 at 13:00

3 Answers 3

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)
answered Apr 6, 2013 at 12:33
Sign up to request clarification or add additional context in comments.

2 Comments

Observer.__init__(self) isn't it a calling to the super class constructor ?
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.
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.

answered Apr 6, 2013 at 12:41

Comments

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.

answered Apr 6, 2013 at 12:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.