A newbie metaclass question
Peter Otten
__peter__ at web.de
Sun May 22 12:26:52 EDT 2005
could ildg wrote:
> When I try to learn metaclass of python by article at this place:
> http://www.python.org/2.2/descrintro.html#metaclasses,
> I changed the autosuper example a little as below:
> <code>
> class autosuper(type):
> def __init__(cls,name,bases,dict):
> super(autosuper,cls).__init__(name,bases,dict)
> setattr(cls,"_%s__super" % name, super(cls))
> print "in metaclass: ", super(cls)
>
> class A:
> __metaclass__ = autosuper
> def meth(self):
> print "in class A: ", self.__super
>
> a=A()
> a.meth()
> </code>
> The result is as below:
> in metaclass: <super: <class 'A'>, NULL>
> in class A: <super: <class 'A'>, <A object>>
>
> The 2 line are not the same. Why?
This particular difference has more to do with the descriptor protocol than
your custom metaclass. Instead of returning a class attribute unaltered, if
present, its __get__() method is called. E. g.:
>>> class A(object):
... pass
...
>>> class Descr(object):
... def __get__(self, *args):
... print "args:", args
... return 42
...
>>> A.attr = Descr()
>>> A.attr
args: (None, <class '__main__.A'>)
42
>>> A().attr
args: (<__main__.A object at 0x402ad62c>, <class '__main__.A'>)
42
And now let's make sure:
>>> hasattr(super(A), "__get__")
True
a 'super' object has a __get__() method, and is therefore free to give you
back whatever it chooses to. (It can detect whether it's called by an
instance or a class by checking its first argument).
You might have found some hints in the text you quote, but a detailed
explanation is here:
http://users.rcn.com/python/download/Descriptor.htm
> The metaclass of python is kinda difficult for me.
IIRC you were about to learn the OO basics just a few days ago. In that
situation I would put metaclasses _very_ low on my list of priorities.
Peter
More information about the Python-list
mailing list