0

I have the following class in python:

class Foo():
    def __init__(self):
        self.id=8
        self.value=self.get_value() #Mark-1
    def get_value(self):
        pass
    def should_destroy_earth(self):
        return self.id ==42

class Baz(Foo):
    def get_value(self,some_new_parameter):
        pass

Here, i can create an object of class Foo as such:

ob1 = Foo() # Success

However, if i try to create an object of Baz, it throws me an error:

Ob2 = Baz() # Error

  File "classesPython.py", line 20, in <module>
    ob2 = Baz()
  File "classesPython.py", line 4, in __init__
    self.value=self.get_value()
TypeError: get_value() takes exactly 2 arguments (1 given)

If i remove the "self.get_value" in 3rd line of class Foo, i can create an object of class Baz.

Isn't is the case that when we inherit a class in python, the init method of the superclass isn't inherited by the subclass and we need to explicitly call them (e.g. Superclass.init(self) )?

So when i create an object of Baz, the __init__method of the Foo() class isn't invoked by default. So why can i not create the object for Baz ?

2
  • 2
    Isn't the real problem here that Baz doesn't actually support the same interface as Foo, and therefore shouldn't be a subclass of it? Could you give a less abstract example? Commented May 16, 2016 at 21:49
  • Yes, you are correct, but this is more towards understanding the idiomatic approach of python. Commented May 16, 2016 at 21:58

2 Answers 2

2

No, you have some fundamental misunderstanding there. The __init__ method of Foo certainly is inherited by Baz.

Python will assume you want the same implementation of __init__ for the subclass, because you didn't implement anything else. You'll have to explicitly define it yourself in Baz, if you don't want that behaviour.

Sign up to request clarification or add additional context in comments.

Comments

1

Isn't is the case that when we inherit a class in python, the init method of the superclass isn't inherited by the subclass and we need to explicitly call them (e.g. Superclass.init(self) )?

No, this is only the case if the subclass has an __init__ method.

1 Comment

I see, so i made a init method in the subclass Baz and now i can create an object. So the concept here is, if i inherit superclass the init method gets executed only if i don't define init method for the derived class. Is my assertion correct?

Your Answer

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.