B
Bruno Desthuilliers
Steven D'Aprano a écrit :
Nope, it doesn't work with computed attributes (properties, descriptors,
....).
The most obvious solution is the decorator pattern - which is somewhat
the op was trying to do.
Another solution is to dynamically add a __getitem__ method to obj
before using'em that way, either by setting explicitly the method as an
attribute of the object's class or by using the import_with_metaclass()
trick from David Mertz.
(snip)
If I have understood you, you have some object like such:
obj.foo = 1
obj.bar = 2
obj.spam = 'a'
obj.eggs = 'b'
say.
You want to use it something like this:
print "My object has fields %(foo)s; %(bar)s; %(spam)s; %(eggs)s." % obj
except that doesn't work. So I would simply change the reference to obj to
obj.__dict__ and it should do exactly what you want.
Nope, it doesn't work with computed attributes (properties, descriptors,
....).
The most obvious solution is the decorator pattern - which is somewhat
the op was trying to do.
Another solution is to dynamically add a __getitem__ method to obj
before using'em that way, either by setting explicitly the method as an
attribute of the object's class or by using the import_with_metaclass()
trick from David Mertz.
(snip)
+1 on this !-)It really does help to explain what your functional requirements are,
instead of focusing on one, possibly pointless, implementation.