Python 3 Patterns & Idioms / src / Metaclasses.rst



Example of self-registration of subclasses.

Version 1: metaclass approach.

(following is cribbed from comp lang python, posting by Nick Craig-Wood January 8, 2009). He noted it was untested, will require rewriting:

class Field(object):
    registry = []
    class __metaclass__(type):
        def __init__(cls, name, bases, dict):
    def __new__(cls, a):
        if cls != Field:
            return object.__new__(cls, a)
        for subcls in cls.registry:
            if subcls == Field:
                return subcls(a)
            except ValueError:
        raise ValueError("Couldn't find subclass")
    def __init__(self, input):
        super(Field, self).__init__(input) = input

# Raise a ValueError in init if not suitable args for this subtype

class IntegerField(Field):
    def __init__(self, s):
        s = int(s)
        super(IntegerField, self).__init__(s)
        self.s = s

class ListField(Field):
    def __init__(self, s):
        if ',' not in s:
            raise ValueError("Not a list")
        super(ListField, self).__init__(s)
        self.s = s.split(',')

class StringField(Field):

Further Reading

Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.