properties and formatting with self.__dict__

Mark McEahern marklists at mceahern.com
Sun Feb 23 20:36:24 EST 2003


[Bengt Richter]
> self.__dict__ is not looking in the right namespace, because
> self.__dict__[name] is not the same as getattr(self, name),
> which is what you need in order to access self.name and find
> class variables and properties.
> 
> I'm not sure if you want to call accessing the right namespace
> a "workaround" (obvious or not), but you can do it with a class
> instance that acts like a dict for the attribute names, e.g.,
> try the following (I added quotation marks and a closing '>'
> to the template to make the output easier to see):
> 
> ====< attrns.py >======================================
> #!/usr/bin/env python
> 
> class AttrNS(object):
>     def __init__(self, obj): self.obj = obj
>     def __getitem__(self, key): return getattr(self.obj, key)

[snip]

That's perfect!  Thanks!

// m
-






More information about the Python-list mailing list