How to Achieve Inheritance&Polymorphism of Static Methods in Python

The aim of this page📝 is to explain how static methods behave in presence of inheritance. In other words how to modify a static method for the different requirements of a derived/child class to get a polymorphic behavior. OOP stuff…

Pavol Kutaj
2 min readOct 25, 2022
  • first, let’s have a little class defining a shipping container
  • it has a couple of instance attributes and 1 static method for id generation
  • if needed, see the details on How to Define Static Methods in Python
""" PARENT """
class ShippingContainer:

@staticmethod
def _make_id():
return "foo"

def __init__(self, owner_id, contents):
self.owner_id = owner_id
self.contents = contents
self.id = ShippingContainer._make_id()
  • let’s introduce a subclass of a shipping container called refrigerated shipping containers
  • and change the id for this particular (bar instead of foo)
  • → I’ll define another static method in the class body
""" CHILD """
class RefrigeratedShippingContainer(ShippingContainer):
@staticmethod
def _make_id():
return "bar"
  • however, the id above is not working as expected, the id is still foo
>>> r = RefrigeratedShippingContainer(owner_id="MPR", contents=["books"])
>>> r.id
'foo'
  • in the parent class initializer you call the static method through a specific class prefix
  • => ShippingContainer._make_id() <=
  • to get the intended polymorphic override in your child class, we need to call the static method on an instance
  • note that testing directly calling the derived class returns also a correct result (bar)
>>> RefrigeratedShippingContainer._make_id(owner_id="MPR", contents=["books"])
'bar'
>>> r2 = RefrigeratedShippingContainer(owner_id="MPR", contents=["poems"])
>>> r._make_id()
'bar'
  • again, the derived class is called
  • we can get polymorphic override — but only when we call a method from the instance.
  • not when we call the method through the class.
>>> r = RefrigeratedShippingContainer("MAE", ["fish"])
>>> r.id
'foo'
  • if we are after the polymorphic dispatch of the static method, we need to modify the _make_id() in the base class
""" BEFORE """

def __init__(self, owner_id, contents):
self.owner_id = owner_id
self.contents = contents
self.bic = ShippingContainer._make_id()
# # ...^^^^^^^^^^^^^^^^^^ incorrect

""" FIXED """

def __init__(self, owner_id, contents):
self.owner_id = owner_id
self.contents = contents
self.bic = self._make_id( )
# .....^^^^ switched from class-prefix to instance-prefix ('self')

>>> r = RefrigeratedShippingContainer("MRP", ["books"])
>>> r.id
'bar'
^ SOLVED

--

--

No responses yet