[Tutor] Intercepting methods calls

Andreas Kostyrka andreas at kostyrka.org
Thu Jun 5 12:06:34 CEST 2008


On Wednesday 04 June 2008 18:18:04 you wrote:
> > Well, let's start the ball rolling then.
> >
> > __getattribute__
> > __getattr__
> > Metaclasses
> > decorators
> > properties
> > __init__
>
> Okay, I'll bite. I asked here a week or two ago about creating a
> custom dummy object that returns a blank string no matter what you do
> with it, or what attribute you try to call on it. Very helpful answers
> led to the following:
>
>
> class Dummy(object):
>    def __init__(self,**atts):
>      self.__dict__.update(atts)
>
>    def __repr__(self):
>      return ''
>
>    def __getattr__(self, attr):
>      return ''
>
> The resulting object return a blank string for everything, except
> attributes created by keyword args you pass to __init__. But if you
> try to call a random method on a Dummy, say:
>
> d = Dummy()
> d.notamethod()
>
> You get "str object is not callable", ie 'notamethod' is first caught
> by __getattr__, turned into an empty string, and called. So what
> recourse do I have here to detect that the attribute is getting
> called, and have that return a blank string too?

well, don't return a string :-P

class CallableString(str):
   def __call__(self, *args, **kw):
      return self

And now instead of return '', write return CallableString('')

Problem solved.

Andreas

>
> Curious,
> E


-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/tutor/attachments/20080605/f8719358/attachment.pgp>


More information about the Tutor mailing list