Override


#1

My doubt is that ,in python why we also need to redefine the method again which has already been defined in the parent class.
According to me, the inheritance should Inherit the parent definition ?
Can somebody help me.
Please somebody tell me why we have to redefine the method again which has already been defined in parent class


#2

Difficult to say without context, a child class inherits all the methods and member variables (python terminology used here, given its unclear which language is used) or properties (JS) of parent class

but for a child class, it might be desired to overwrite certain methods.

I wrote a web-app in python, there was a built-in class, ListVIew which could be used as parent class, which can display a list of information, for example: users or status updates) but for the different views (child class) i needed to list different result (sometimes the users, sometimes the status updates). This could easily be achieved by overwriting a single method

However, each view still shared a lot of properties with parent class, so inheritance was still profitable. I just needed to overwrite a single method to get the status update for one view or the users for another view , while keeping all the other properties of parent class

in a larger program, inheritance done right can be very powerful. Good design of your classes is important, inheritance and overwriting parent methods by child classes included


#3

Can you tell me any source for learning inheritance in python.


#4

Inheritance itself is simple, a class can inherit from one or more classes.

so for example:

class A(object):
    # do something


class B(object):
    # do something


class C(A,B):
    # do something

C is the child of A and B, so A and B are the parent classes of C

C itself could also be a parent:

class D(C):

now C is a child of A and B but its also a parent class of D.

this is inheritance, this it. There isn’t more too it.

This is where it gets interesting:

class A(object):
    def example(self): 
         print "hello A"

class B(object):
    def example(self): 
         print "hello B"

class C(A,B):
    def example(self): 
         super(C, self).example()
         print "hello world"

c = C()
c.example()

super() allows us to call parent method, but C inherits from both A and B, so will this program print:

hello A
hello world

or:

hello B
hello world

this is called MRO (method resolution order), for which you can find many good sources:

https://makina-corpus.com/blog/metier/2014/python-tutorial-understanding-python-mro-class-search-path

the other thing which is tricky about classes (OOP) is a good design of your classes, you can read about it (google: oop design), but this is also a lot of practice


#5

Thanks Stetim94._


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.