use Userdict for class __dict__

Gordon McMillan gmcm at hypernet.com
Wed Dec 1 16:47:13 EST 1999


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




More information about the Python-list mailing list