Method Overriding

suggest change

Here is an example of basic overriding in Python (for the sake of clarity and compatibility with both Python 2 and 3, using new style class and print with ()):

class Parent(object):
    def introduce(self):
        print("Hello!")

    def print_name(self):
        print("Parent")
    
    
class Child(Parent):
    def print_name(self):
        print("Child")
    
    
p = Parent()
c = Child()

p.introduce()
p.print_name()

c.introduce()
c.print_name()

$ python basic_override.py 
Hello!
Parent
Hello!
Child

When the Child class is created, it inherits the methods of the Parent class. This means that any methods that the parent class has, the child class will also have. In the example, the introduce is defined for the Child class because it is defined for Parent, despite not being defined explicitly in the class definition of Child.

In this example, the overriding occurs when Child defines its own print_name method. If this method was not declared, then c.print_name() would have printed "Parent". However, Child has overriden the Parent’s definition of print_name, and so now upon calling c.print_name(), the word "Child" is printed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Method Overriding:

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
93 Method Overriding
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve