Basic Metaclasses

suggest change

When type is called with three arguments it behaves as the (meta)class it is, and creates a new instance, ie. it produces a new class/type.

Dummy = type('OtherDummy', (), dict(x=1))
Dummy.__class__              # <type 'type'> 
Dummy().__class__.__class__  # <type 'type'>

It is possible to subclass type to create an custom metaclass.

class mytype(type):
    def __init__(cls, name, bases, dict):
        # call the base initializer
        type.__init__(cls, name, bases, dict)

        # perform custom initialization...
        cls.__custom_attribute__ = 2

Now, we have a new custom mytype metaclass which can be used to create classes in the same manner as type.

MyDummy = mytype('MyDummy', (), dict(x=2))
MyDummy.__class__              # <class '__main__.mytype'>
MyDummy().__class__.__class__  # <class '__main__.mytype'>
MyDummy.__custom_attribute__   # 2

When we create a new class using the class keyword the metaclass is by default chosen based on upon the baseclasses.

>>> class Foo(object):
...     pass

>>> type(Foo)
type

In the above example the only baseclass is object so our metaclass will be the type of object, which is type. It is possible override the default, however it depends on whether we use Python 2 or Python 3:

A special class-level attribute __metaclass__ can be used to specify the metaclass.

class MyDummy(object):
    __metaclass__ = mytype
type(MyDummy)  # <class '__main__.mytype'>

A special metaclass keyword argument specify the metaclass.

class MyDummy(metaclass=mytype):
    pass
type(MyDummy)  # <class '__main__.mytype'>

Any keyword arguments (except metaclass) in the class declaration will be passed to the metaclass. Thus class MyDummy(metaclass=mytype, x=2) will pass x=2 as a keyword argument to the mytype constructor.

Read this in-depth description of python meta-classes for more details.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Metaclasses:
* Basic Metaclasses

Table Of Contents
2 Filter
3 List
7 Loops
18 Metaclasses
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve