Designing a Class Factory

As mentioned, class factories are functions that create and return a class. It can create a class at the coding time (using class keyword) and as well as during run time (using the type). Let’s start with how to design a class factory and create a class at the coding time, then we look into the scenario of creating a class during run time.

Class Factory and class keyword

Designing a class factory using the class keyword is nothing but creating a function that holds a class. Let’s see the below code:

Python3




def apple_function():
    """Return an Apple class, built using the 
    class keyword"""
    class Apple(object):
        def __init__(self, color):
            self.color = color
  
        def getColor(self):
            return self.color
    return Apple
  
  
# invoking class factory function
Apple = apple_function()
appleObj = Apple('red')
print(appleObj.getColor())


Output

red

Class Factory and type

Using type we can create classes dynamically. But doing so will leave the functions in the namespace along with the class. Let’s look into the code to understand it better.

Python3




def init(self, color):
    self.color = color
  
  
def getColor(self):
    return self.color
  
  
Apple = type('Apple', (object,), {
    '__init__': init,
    'getColor': getColor,
})
  
appleRed = Apple(color='red')
print(appleRed.getColor())


Output

red

The above code shows how to create class dynamically. But the problem is that the functions such as init and getColor are cluttering the namespace and also we won’t be able to reuse the functionality. Whereas, by using a class factory, you can minimize the clutter and can reuse the function when in need. Let’s look at the below code.

Python3




def create_apple_class():
    def init(self, color):
        self.color = color
  
    def getColor(self):
        return self.color
  
    return type('Apple', (object,), {
        '__init__': init,
        'getColor': getColor,
    })
  
  
Apple = create_apple_class()
appleObj = Apple('red')
print(appleObj.getColor())


Output

red

It is important to note that multiple calls to create_apple_class will return distinct classes.

Class Factories: A powerful pattern in Python

A Class Factory is a function that creates and returns a class. It is one of the powerful patterns in Python. In this section, we will cover how to design class factories and the use cases of it.

Similar Reads

Designing a Class Factory

As mentioned, class factories are functions that create and return a class. It can create a class at the coding time (using class keyword) and as well as during run time (using the type). Let’s start with how to design a class factory and create a class at the coding time, then we look into the scenario of creating a class during run time....

When you should write Class Factories

...

Summary

...

Contact Us