Overriding
Date: February 10th 2016
Last updated: February 7th 2017
You can override attributes and methods of a class.
Overriding attributes:
Create BaseClass to inherit in DerivedClass
class BaseClass(object):
def __init__(self, name):
self.name = name
self.address = address
class DerivedClass(BaseClass):
def __init__(self):
super(DerivedClass, self).__init__(name, address)
self.name = "Ray"
d = DerivedClass('john', '42 wallaby way')
print(d.name)
print(d.address)
# Ray
# 42 wallaby way
DerivedClass inherits name and address from BaseClass. But after instantiating both parameters, name is overriden to 'Ray'.
Overriding methods:
# Create method for BaseClass to override
class BaseClass(object):
def __init__(self, name, address):
self.name = name
self.address = address
def printName(self):
print(self.name)
class DerivedClass(BaseClass):
def __init__(self, name, address):
super(DerivedClass, self).__init__(name, address)
self.name = "Ray"
# note that there is no printName in DerivedClass
# printName() is available in DerivedClass
d = DerivedClass('john', '42 wallaby way')
d.printName()
# output
# Ray
Note: The output for self.name is still being manually changed to 'Ray' in DerivedClass. There is no printName method in DerivedClass but inherits it from BaseClass. Therefore, printName simply returns the attribute I manually changed. If I add a printName function to DerivedClass I can override the method to return the address instead of a name.
class BaseClass(object):
def __init__(self, name, address):
self.name = name
self.address = address
def printName(self):
print(self.name)
class DerivedClass(BaseClass):
def __init__(self, name, address):
super(DerivedClass, self).__init__(name, address)
self.name = "Ray"
# note I am using the same method name - printName()
def printName(self):
print(self.address)
d = DerivedClass('john', '42 wallaby way')
d.printName()
# output
# 42 wallaby way