Python
  Home arrow Python arrow Page 3 - Metaclasses: Blueprints of Blueprints
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PYTHON

Metaclasses: Blueprints of Blueprints
By: Peyton McCullough
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    2005-12-13


    Table of Contents:
  • Metaclasses: Blueprints of Blueprints
  • The Barebones
  • Adding Some Meat
  • Using Metaclasses
  • A class named G

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Metaclasses: Blueprints of Blueprints - Adding Some Meat
    ( Page 3 of 5 )

    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
    4
    >>> A.y
    19
    >>> 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'>
    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()
    True

    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
     

       

    PYTHON ARTICLES

    - 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
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek