SeasonalShot
SeasonalShot

Reputation: 2569

Python class object creation in inheritance

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 ?

Upvotes: 0

Views: 207

Answers (2)

Rushy Panchal
Rushy Panchal

Reputation: 17532

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.

Upvotes: 1

wim
wim

Reputation: 362557

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.

Upvotes: 2

Related Questions