Home arrow Python arrow Page 3 - Metaclasses: Blueprints of Blueprints

Adding Some Meat - Python

We all know that objects are created from classes. But can a class be created from a class? Yes it can; this is called a metaclass. They give us a great deal of power when it comes to changing the behavior of a class. Python 2.2 supports metaclasses. Peyton McCullough explains.

  1. Metaclasses: Blueprints of Blueprints
  2. The Barebones
  3. Adding Some Meat
  4. Using Metaclasses
  5. A class named G
By: Peyton McCullough
Rating: starstarstarstarstar / 13
December 13, 2005

print this article



Now let's add some more substance to the picture, since the purpose of metaclasses is not to just sit there and look pretty. We can start by sticking some variables into our metaclass:

>>> class MetaA ( type ):
 x = 4
 y = 19
 z = ( 1, 2, 3 )

The classes created out of this metaclass will have the same variables:

>>> class A ( object ):
 __metaclass__ = MetaA

>>> A.x
>>> A.y
>>> A.z
(1, 2, 3)

However, this isn't a very good use at all for metaclasses, since a regular class could do the same thing if A were to subclass it, and the process would be a bit simpler. However, just as a normal class can initialize an object, a metaclass can initialize a class:

>>> class MetaB ( type ):
 def __init__ ( cls, name, bases, dct ):
  print cls
  print name
  print bases
  print dct

As you can see, the __init__ method accepts four variables: cls, name, bases and dct. The cls variable can be compared to self in normal classes. However, since we are dealing with a class instead of an object, it is named a bit differently. The name variable simply contains the name of the class, the bases variable contains a tuple of base classes, and the dct variable contains a dictionary of attributes. Another common name for this last variable is dict, though that gets in the way of the dictionary type since they share the same name in that situation. The __init__ method is called as soon as our class is created:

>>> class B ( object ):
 __metaclass__ = MetaB
 x = "c"
 z = 1
 y = z + 3
 def __init__ ( self ):
  print z + y
 def test ( self ):
  print x

<class '__main__.B'>
(<type 'object'>,)
{'__module__': '__main__', '__metaclass__': <class '__main__.MetaB'>, 'test': <function test at 0x00B4A570>, 'y': 4, 'x': 'c', 'z': 1, '__init__': <function __init__ at 0x00B4A2B0>}

The MetaB class simply displays the name of each variable. As you can see above, the dictionary of attributes provides us with an interesting link to the class's internals. This is a significant feature, and it gives us a lot of power over classes. It allows us to make some pretty interesting modifications to things that would not otherwise be possible. Consider class C:

>>> class C:
 def one ( self ):
  return True
 five = four = three = two = one

Now, suppose that we didn't want to create that chain at the end, which assigns alternate names for the one method. We could use a metaclass to eliminate the need for that. For example, we could define the method as multi_one_two_three_four_five and have a metaclass rip it apart for us, creating methods one through five. It's actually pretty simple:

>>> class MetaD ( type ):
 def __init__ ( cls, name, bases, dct ):
  # Loop through the dictionary
  for key, value in dct.iteritems():

   # If the key starts with multi_, perform our work
   if key.find ( 'multi_' ) == 0:

    # Split the name to get the aliases
    aliases = key.split ( '_' ) [ 1: ]

    # Define the new names
    for alias in aliases:
     setattr ( cls, alias, value )

We simply loop through the dictionary, and if the attribute name starts with “multi_”, then we break it apart at each underscore and re-assign the value to each piece of the name. Here's our metaclass in action:

>>> class D ( object ):
 __metaclass__ = MetaD
 def multi_one_two_three_four_five ( self ):
  return True

>>> x = D()
>>> x.one
<bound method D.multi_one_two_three_four_five of <__main__.D object at 0x00B4C3D0>>
>>> x.two
<bound method D.multi_one_two_three_four_five of <__main__.D object at 0x00B4C3D0>>
>>> x.three()

Metaclass MetaD might not be completely practical, but it demonstrates the power of metaclasses. We can use metaclasses to alter the behavior of classes, allowing for new levels of control over classes.

>>> More Python Articles          >>> More By Peyton McCullough

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates


Dev Shed Tutorial Topics: