__get__() example (python descriptors)

354 views
Skip to first unread message

Kumar McMillan

unread,
Mar 14, 2008, 5:26:27 PM3/14/08
to secrets-of-the-f...@googlegroups.com
someone had asked the question, what does __get__() do? I answered by
explaining two classes, one defining __get__(), but thought it would
be better if I showed what I meant in code:

>>> class InfoDescriptor(object):
... def _new_info(self, msg):
... return "intercepted! '%s'" % msg
... def __get__(self, logger, logger_class):
... return self._new_info
...
>>> class Logger(object):
... info = InfoDescriptor()
...
>>> log = Logger()
>>> log.info('something happened')
"intercepted! 'something happened'"
>>>

As you can see, log.info() returns __get__() instead of log.info itself.

There is a bit more info here:
http://users.rcn.com/python/download/Descriptor.htm ... but I'm still
not sure of a real world, practical example for using descriptors.
Maybe someone else can post a more realistic example.

-Kumar

Daryl Spitzer

unread,
Mar 17, 2008, 8:54:38 PM3/17/08
to secrets-of-the-f...@googlegroups.com
Marty Alchin blogs about Python Descriptors and Django in
http://gulopine.gamemusic.org/2007/nov/23/python-descriptors-part-1-of-2/.
(I haven't read it carefully yet--and I haven't even looked at part
2.)

--
Daryl

Reply all
Reply to author
Forward
0 new messages