Mr. Sigma.
Mr. Sigma.

Reputation: 435

How to call a function of a parent class with its own instance variables without overriding child's instances?

Suppose I have the following code snippet.

class Parent(): 
    def __init__(self):
        self.where = 'parent'

    def show(self): 
        print("Inside Parent", self.where) 

class Child(Parent): 
    def __init__(self):
        self.where = 'child'
        super(Child, self).show()
        self.show()

     def show(self): 
        print("Inside Child", self.where) 

# Driver's code 
obj = Child()  

But the output is

Inside Parent, child
Inside Child, child

I wanted the output exactly to be (want the parent to be printed first)

Inside Parent, parent
Inside Child, child

How can I achieve it? Basically it is to call parent class in child class where parent class should use its own instance variable.

Upvotes: 1

Views: 85

Answers (3)

Mr. Sigma.
Mr. Sigma.

Reputation: 435

Thanks to @jasonharper, it was pretty straightforward. The catch was to privatize where as __where variables in each of the parent and child class.

class Parent(): 
    def __init__(self):
        self.__where = 'parent'

    def show(self): 
        print("Inside Parent", self.__where) 

class Child(Parent): 
    def __init__(self):
        self.__where = 'child'
        super().__init__()
        super().show()
        self.show()

    def show(self): 
        print("Inside Child", self.__where) 

# Driver's code 
obj = Child()  

Upvotes: 1

MeBex
MeBex

Reputation: 488

You need to call the __init__() function of the Parent class:

class Parent():
    def __init__(self):
        self.where = 'parent'

    def show(self):
        print("Inside Parent", self.where)

class Child(Parent):
    def __init__(self):
        self.where = 'child'
        self.show()
        super().__init__()
        super().show()

    def show(self):
        print("Inside Child", self.where)

Upvotes: 1

wstk
wstk

Reputation: 1270

You need to remember to call the __init__() method of the super class.

Note, you have tagged this as Python3, so you can just use

super().__init__()
super().show()

No need to use the name of the child class inside the parentheses in this case.

Upvotes: 0

Related Questions