create a subclass with a constructor in python

To create a subclass with a constructor in Python, follow these steps:

  1. Define the parent class with its constructor.
main.py
class Parent:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2
100 chars
5 lines
  1. Define the child class and indicate the parent class in parentheses after the declaration.
main.py
class Child(Parent):
    def __init__(self, arg1, arg2, arg3):
        Parent.__init__(self, arg1, arg2)
        self.arg3 = arg3
130 chars
5 lines
  1. Call the constructor of the parent class using the super() function inside the constructor of the child class.
main.py
class Child(Parent):
    def __init__(self, arg1, arg2, arg3):
        super().__init__(arg1, arg2)
        self.arg3 = arg3
125 chars
5 lines
  1. Use the child class with its constructor passing all arguments needed including the parent's constructor's arguments.
main.py
child_class = Child(arg1_value, arg2_value, arg3_value)
56 chars
2 lines

Note that the child class can access all attributes and methods from its parent class.

gistlibby LogSnag