anil maran wrote:
> hi pygurus
> can you please tell me why we need metaclasses and how to use them

Hmm...metaclasses are an advanced topic, first exposure to them usually 
causes one's brain to explode. Fortunately the condition is only 
temporary :-)

Basically a metaclass is the type of a class, or the type of a type. 
Think about it this way - every object has a type. The type of 1 is int, 
the type of 'a' is str.

In [16]: type(1)
Out[16]: <type 'int'>

In [17]: type('a')
Out[17]: <type 'str'>

Note that <type 'int'> is just the printed representation of the type int:
In [19]: type(1) == int
Out[19]: True

In [20]: print int
<type 'int'>

But int and str are themselves objects - what is their type?

In [18]: type(int)
Out[18]: <type 'type'>

In [21]: type(str)
Out[21]: <type 'type'>

Why might you care? In general, it is the type of an object that 
determines its behaviour. The behaviour of an int is determined by the 
int type. What determines the behaviour of a class? Its type! So if you 
want to customize the behaviour of a class, you create a custom metatype 
for the class.

That is a very brief introduction. Here are some relatively introductory 
articles. You can find more examples by searching the Python Cookbook 
and comp.lang.python for "metaclass". Don't expect to understand this 
the first time.
http://www-128.ibm.com/developerworks/linux/library/l-pymeta.html
http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/

Here is Guido's brief explanation:
http://www.python.org/download/releases/2.2.3/descrintro/#metaclasses

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to