Cool object trick
Bengt Richter
bokr at oz.net
Sat Dec 18 03:08:17 EST 2004
On Sat, 18 Dec 2004 08:39:47 +0100, "Fredrik Lundh" <fredrik at pythonware.com> wrote:
>Carl Banks wrote:
>
>> For example:
>>
>> . def lookup_reference(key):
>> . ....
>> . return Bunch(title=title,author=author,...)
>>
>> The code quickly and easily returns a object with the desired keys.
>> The code that calls this function would access the return values
>> directly, like this:
>>
>> . m = lookupreference()
>> . print "%s was written by %s" % (m.title,m.author)
>>
>> You could still use a dict for this, but a Bunch class neater and more
>> concise (not to mention less typing).
>
>this is how your example looks in Python:
>
> def lookup_reference(key):
> ...
> return dict(title=title, author=author, ...)
>
> m = lookup_reference(...)
> print "%(title)s was written by %(author)s" % m
>
>(if you fix the bug in your example, and count the characters, you'll find
>that my example is a bit shorter)
>
>with enough keys, you can also save typing by using dummy object instead
>of a dictionary, and getting rid of the locals in lookup_reference:
>
> def lookup_reference(key):
> m = object()
> m.title = ... assign directly to return struct members ...
> m.author = ...
> return m
>
> m = lookup_reference(...)
> print "%(title)s was written by %(author)s" % vars(m)
>
>>> m = object()
>>> m.title = 'not so fast ;-)'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'object' object has no attribute 'title'
>>> m=type('',(),{})()
>>> m.title = 'not so fast ;-)'
>>> m.title
'not so fast ;-)'
Regards,
Bengt Richter
More information about the Python-list
mailing list