PythonAdd __init__() Function
Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its parent.
We want to add the__init__()
function to the child class (instead of thepass
keyword).
Note: The__init__()
function is called automatically every time the class is being used to create a new object.
Example
Add the__init__()
function to theStudent
class:
def __init__(self, fname, lname):
#add properties etc.
When you add the__init__()
function, the child class will no longer inherit the parent's__init__()
function.
Note: The child's__init__()
functionoverrides the inheritance of the parent's __init__()
function.
To keep the inheritance of the parent's__init__()
function, add a call to the parent's__init__()
function:
Example
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the__init__()
function.
Related Pages
Python Inheritance TutorialCreate Parent ClassCreate Child Classsuper FunctionAdd Class PropertiesAdd Class Methods