Inheritance in Python
Inheritance in Python
Inheritance
The code below will first call upon the __init__ method (using super()) of
the parent class to create the attributes name, age, and occupation. The
__init__ method is extended when the attribute secret_identity is added
to the Superhero class.
class Superhero(Person):
def __init__(self, name, age, occupation, secret_identity):
super().__init__(name, age, occupation)
self.secret_identity = secret_identity
class Superhero(Person):
def __init__(self, name, age, occupation, secret_identity, nemesis):
super().__init__(name, age, occupation)
self.secret_identity = secret_identity
self.nemesis = nemesis
class Superhero(Person):
def __init__(self, name, age, occupation, secret_identity, nemesis):
def reveal_secret_identity(self):
print(f"My real name is {self.secret_identity}.")
hero.reveal_secret_identity()
challenge
class Superhero(Person):
def __init__(self, name, age, occupation, secret_identity, nemesis):
super().__init__(name, age, occupation)
self.secret_identity = secret_identity
self.nemesis = nemesis
def reveal_secret_identity(self):
print(f"My real name is {self.secret_identity}.")
def say_nemesis(self):
print(f"My nemesis is {self.nemesis}.")
Overriding a Method
Extending a class means adding new attributes or methods to the child
class. Another way to add new functionality to a child class is through
method overriding. Overriding a method means to inherit a method from
the parent class, keep its name, but change the contents of the method.
def say_hello(self):
print(f"I am {self.name}, and criminals fear me.")
hero.say_hello()
challenge
def say_age(self):
print(f'Young or old I will trimph over evil')
print(help(Superhero))
Notice that there is no section that says Methods inherited from Person:.
Does that mean that the Superhero can no longer use the original say_age
and say_hello methods? No, the child class can still call the methods from
the parent class. However, calling say_hello or say_age will not print the
same string as the parent class. Instead, using the super() keyword gives a
child class access to the original methods. Add the following method to the
Superhero class and then call it.
def old_say_hello(self):
super().say_hello()
hero.old_say_hello()
challenge
Solution
def old_say_age(self):
super().say_age()
hero.old_say_age()