metaclasses: timestamping instances
Steve Holden
steve at holdenweb.com
Sat Sep 1 12:07:33 EDT 2007
km wrote:
> Hi all,
>
> I have extended a prototype idea from Alex Martelli's resource on
> metaclasses regarding time stamping of instances.
>
> <code>
> import time
> class Meta(type):
> start = time.time()
> def __call__(cls, *args, **kw):
> print 'Meta start time %e'%cls.start
> x = super(Meta, cls).__call__(*args, **kw)
> current_time = time.time()
> x._created = current_time - Meta.start
> Meta.start = time.time()
> return x
>
> class X(object):
> __metaclass__ = Meta
> class Y(X):
> __metaclass__ = Meta
> pass
> a = X()
> print 'a time stamp %e'%a._created
> b = Y()
> print 'b time stamp %e'%b._created
> print abs(a._created - b._created)
> </code>
>
> I donot understand the difference between
> 1) setting __metaclass__ to 'Meta' in class Y
> 2) not setting __metaclass__ to Meta in class Y
>
> Why is the difference in behaviour of time stamping between 1 & 2 ?
>
> kindly enlighten
>
I don't see and difference. The rules for establishing the metaclass of
a class are fairly well defined: see
http://docs.python.org/ref/metaclasses.html
which says
* If dict['__metaclass__'] exists, it is used.
* Otherwise, if there is at least one base class, its metaclass is
used (this looks for a __class__ attribute first and if not found, uses
its type).
* Otherwise, if a global variable named __metaclass__ exists, it is
used.
* Otherwise, the old-style, classic metaclass (types.ClassType) is
used.
By the second rule it would appear that the metaclass of X is the same
as that of Y even if the __metaclass__ assignment is commented out, and
informal testing appears to show that this is the case.
Debugging with Wing IDE and examining the classes at a breakpoint shows
this to be true (even after Y's __metaclass__ assignment is commented out):
>>> X.__metaclass__
<class '__main__.Meta'>
>>> Y.__metaclass__
<class '__main__.Meta'>
>>>
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
More information about the Python-list
mailing list