Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I need to initialize the parent class when inheriting?

Tags:

python

super

If I am inheriting from a class and not changing anything in a method, is it required to use super to initialize the method from the parent class?

class A:

   def __init__(self):
       self.html = requests.get("example.com").text


class B(A):

    def __init__(self):
        # is this needed?
        super(B, self).__init__()

    def new_method(self):
        print self.html
like image 453
yayu Avatar asked Nov 22 '25 00:11

yayu


2 Answers

Because you created a __init__ method in your class B, it overrides the method in class A. If you want it executed, you'll have to use super(), yes.

However, if you are not doing anything else in B.__init__, you may as well just omit it:

class A:
   def __init__(self):
       self.html = requests.get("example.com").text

class B(A):
    def new_method(self):
        print self.html

If you want to do anything in addition to what A.__init__() does, then it makes sense to create a B.__init__() method, and from that method, invoke the parent __init__.

like image 121
Martijn Pieters Avatar answered Nov 23 '25 13:11

Martijn Pieters


It's not needed to define the overriding method at all. Python's default behavior is to call the method on the parent class (the next class in the method resolution order) if the current class doesn't override it.

>>> class Foo(object):
...   def __init__(self):
...     print("Foo")
... 
>>> class Bar(Foo): pass
... 
>>> Bar()
Foo
<__main__.Bar object at 0x7f5ac7d1b990>

Notice "Foo" got printed when I initialized a Bar instance.


If you do define the method, you need to call the super class's method (either explicitly or via super) if you want to make sure that it gets called.

like image 37
mgilson Avatar answered Nov 23 '25 14:11

mgilson



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!