Chapter 6Class Factories
As described in Chapter 5, “Metaclasses,” Python classes are also objects. The fact that classes are first-class objects in Python also allows for the possibility to employ other powerful patterns. A class factory is one of these patterns. Essentially, this is a function that creates a class, and does so at runtime. This concept allows for the creation of a class whose attributes are determined, for example, as a result of user input.
This chapter covers class factories, first by reviewing generating classes on the fly, and showing how to do so within functions. Then, it covers a couple of common cases where class factories are valuable.
A Review of type
Recall from the discussion in Chapter 5 that, like other objects in Python, classes are instantiated by a class. For example, say that you create a class, Animal, as shown here:
class Animal(object):
"""A class representing an arbitrary animal."""
def __init__(self, name):
self.name = name
def eat(self):
pass
def go__to__vet(self):
pass
The Animal class is responsible for creating Animal objects when its constructor is called. But, in the same way that Animal creates its objects, so, too, is Animal an object itself. Its class is type, a built-in class in Python that creates all other classes.
type is primary metaclass, and custom metaclasses (as you learned in Chapter 5) subclass type.
It is also possible to invoke type directly to create a class, in lieu of using the class keyword. type takes three ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access