Python 3: Inheritance and super()
Posted by Ed on April 23, 2016
Inheritance in Object Oriented Programming (OOP) means that you create a new class by extending an existing class. For example, suppose we have a class Shape with the attribute position. Then we can create a new class Circle by taking Shape and extending it by a new attribute center:
# Python 3 class Shape(object): def __init__(self, position): self.position = position class Circle(Shape): def __init__(self, position, radius): super().__init__(position) # call __init__() method of base class Shape self.radius = radius def example(): c = Circle( [5, 2], 7.0 ) print("position of circle:", c.position) print("radius of circle:", c.radius) if __name__ == '__main__': example()
With super().__init__() we call the __init__() method of the base class Shape. If you run that program the output is
position of circle: [5, 2] radius of circle: 7.0
References
If you’ve liked this blog post feel free to skim through my other articles here, e.g. I’ve written an introduction to OOP in Python.
Leave a comment