How to Create Named Constructors with Class Methods in Python

The aim of this page📝 is to describe the implementation and benefits of named constructors in Python — aka factory function.

Pavol Kutaj
2 min readSep 8, 2022
  • In python, it s possible for a class to support named constructors
  • Originally, this is a C++ idiom / design pattern
  • A so-called factory method returns an instance of a class
  • The method has a name other than the default __init__(), which allows callers to express intent
  • Therefore, it also allows object construction to be performed with different combinations of arguments
  • The following class method
@classmethod
def create_empty(cls, owner_code):
return cls(owner_code, contents=[])

… accepts owner_code and calls the class to create the (object) instance

  • The whole code contains also a regular initializer, see
class ShippingContainer:

next_serial = 1337

@classmethod
def _generate_serial(cls):
result = cls.next_serial
cls.next_serial += 1
return result

@classmethod
def create_empty(cls, owner_code):
return cls(owner_code, contents=[])

def __init__(self, owner_code, contents):
self.owner_code = owner_code
self.contents = contents
self.serial = ShippingContainer._generate_serial()
  • You can, however, create an object by calling the create_empty "constructor" / "factory function"
  • Of course, if you try to create an instance without any method and with missing arguments you’ll get a TypeError
>>> c = ShippingContainer()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 2 required positional arguments: 'owner_code' and 'contents'
  • To create a regular instance, you provide all the args defined in the __init__()
>>> c = ShippingContainer(owner_code="ABC",contents=['Apples','Oranges'])
  • By calling create_empty(cls, owner_code), you return the class object providing it with
  1. passed owner_code
  2. empty list for contents parameter
  • This would be synonymous with calling
c = ShippingContainer(owner_code="ABC", contents=[])
  • This technique allows defining multiple constructors with different behaviors
  • → adds an extra layer between the class and the __init__() method
  • → avoids adding unnecessary complexity to the __init__() itself
  • → possible to pass different forms of an argument list

--

--

No responses yet