After presenting the latest Packet Coders tech session in our membership last night, around Python OOP (recording here) there was one feature that I wanted to share with you, that is super useful for preventing code duplication when working with Python classes.
This feature (technically a Python method) is called super()
. The TL;DR here is super()
:
is used to provide access to methods and properties of a parent class.
In other words, let's say we have a Router
object. Like so:
class Router:
def __init__(self, vendor, platform):
self.vendor = vendor
self.platform = platform
Let's say we want to create an Mx
object which also includes a site attribute.
We could do this, but as you can see, we are duplicating code.
class Mx(Router):
def __init__(self, vendor, platform, site):
self.vendor = vendor <--- code duplication
self.platform = platform <--- code duplication
self.site = site
Instead, we can use super()
, like so, to access these attributes from the parent class.
class Mx(Router):
def __init__(self, vendor, platform, site):
super().__init__(vendor, platform)
self.site = site
We can now create an instance of our Mx
object like so:
>>> r2 = Mx(vendor="juniper", platform="mx", site="london")
>>> print(r2.site)
london
Good stuff!