Info needed on metaclasses / type-ing

Geert-Jan Van den Bogaerde gvdbogae at vub.ac.be
Sat Mar 23 09:40:24 EST 2002


On Sat, 2002-03-23 at 14:46, Dimitris Garanatsios wrote:
> I recently browsed through an unfinished book of Bruce Eckel, "Thinking in
> Python", Revision 0.1.2
> I can't remember the URL where i got it, but i found it through searching
> for documentation on Python from the main site, www.python.org
> 
> I found the following peace of code there:
> 
> ------------------------------------------------------------------
> 
> #: c01:SingletonMetaClass.py
> class SingletonMetaClass(type):
>     def __init__(cls, name, bases, dict):
>         super(SingletonMetaClass, cls).__init__(name, bases, dict)
>         original_new = cls.__new__
> 
>         def my_new(cls, *args, **kwds):
>             if cls.instance == None:
>                 cls.instance = original_new(cls, *args, **kwds)
>             return cls.instance
> 
>         cls.instance = None
>         cls.__new__ = staticmethod(my_new)
> 
> class bar(object):
>     __metaclass__ = SingletonMetaClass
> 
>     def __init__(self,val):
>         self.val = val
> 
>     def __str__(self):
>         return `self` + self.val
> 
> ...
> #:~
> 
> ------------------------------------------------------------------
> 
> My question is about the "SingletonMetaClass" class.
> I have tried in the past to create my own types using Python and just could
> not find a way of doing that since built-in type objects' structure where
> not documented.
> 
> The "SingletonMetaClass though", as far as i can understand, please help me
> with that, is doing exactly what i wanted: a new type definition. I browsed
> Python's manuals to find more about the attributes and functions that are
> used, but found nothing...
> 
> Could anyone help me find information about the meaning and use of the
> following attributes/functions/objects? These are:
> 
> --- the "__metaclass__" attribute of the "bar" class (derived from object)
> 
> --- the "object" object itself
> 
> --- the "super" function used in the "SingletonMetaClass" class (a class for
> a new type object?)
> 
> --- the "__new__" attribute/method of a class (applies to any class?)
> 
> --- the "staticmethod" function used in the "SingletonMetaClass" class
> 
> --- any additional info about related classes or functions that are not used
> in the above example but exist and are available to use


http://www.python.org/2.2.1/descrintro.html

Geert-Jan





More information about the Python-list mailing list