use Userdict for class __dict__

Gordon McMillan gmcm at hypernet.com
Thu Dec 2 14:22:18 EST 1999


Gang Li writes:

> The proxy only works with instance.   I want something working
> with class, and the class subclass it will inherent the same
> properties.

Under normal circumstances, a class __dict__ (or base class 
__dict__) will be static, since it will be mutated only by an 
explicit reference through the class object. But if that's what 
you really want, you could get at least part of it by doing a 
metaclass. You can't override the definition of a class 
__dict__, though, because getattr, as you found out, assumes 
a real dict (it goes through the C interface, not the Python 
interface). So the metaclass would just use some variation on 
this same proxy trick.
 
> "Gordon McMillan" <gmcm at hypernet.com> wrote in message
> news:1268037651-41672093 at hypernet.com...
> > Gang Li writes:
> >
> > > In order to monitor access of class attributes, I tried to
> > > replace class __dict__ with UserDict.
> > >
> > > class Foo: pass
> > >
> > > class MyUserDict(UserDict.UserDict):
> > >     def __getitem__(self, name):
> > >         ......
> > >
> > > Foo.__dict__ = MyUserDict(Foo.__dict__)
> > >
> > > But python bit me with:
> > >     TypeError: __dict__ must be a dictionary object
> > >
> > > How can I avoid this kind error.
> >
> > Wrap your object in a proxy:
> >
> > class Proxy:
> > def __init__(self, obj=None):
> > self.__obj__ = obj
> > def __getattr__(self,name):
> > print "getattr called for", name
> > return getattr(self.__obj__, name)
> > def __repr__(self):
> > return "Proxy for "+`self.__obj__`
> > __str__ = __repr__
> >
> >
> > - Gordon
> >
> >
> 
> 
> 
> -- 
> http://www.python.org/mailman/listinfo/python-list



- Gordon




More information about the Python-list mailing list