__getatr__ question

Ignacio Vazquez-Abrams ignacio at openservices.net
Wed Oct 3 15:33:15 EDT 2001


On 3 Oct 2001, Jim wrote:

> The following code is used to create a class.  If I make an instance
> of the class called "k", then calling k.func1(23) will print
> "k.func1(23)", and calling k.func2() will print "k.func2()" and return
> 12.  The problem occurs when I nest the functions like this:
> k.func1(k.func2()).  This prints "k.func2()", "k.func2(12)" when I
> really want it to print "k.func2()", "k.func1(12)".  It gets more
> interesting when I do something like k.func1(k.func2() + k.func3()).
> This results in a printout of "k.func2()", "k.func3()", "k.func2(12)".
>
> What's up with this, and it a bug or a feature of python?  It seams
> like the __getattr__ is not being called/refreshed in the external
> function if it is also called inside the function.
>
> Thanks for any help
>
> -Jim
>
> ****** Code *******
>
> class klass:
>
>     def __init__(self, name):
>         self.name = name
>
>     def __getattr__(self, a):
>
>         self.string = a
>         return(self.nop)
>
>     def __repr__(self):
>         return ''
>
>     def nop(self, a = None):
>
>         if (a == None):
>             #pass
>             print self.name + '.' + self.string + '()'
>             return 12
>
>         else:
>             #pass
>             print self.name + '.' + self.string + '(' + str(a) + ')'

It looks as though you're assuming that k.__getattr__() is only called when
the function is called. ASS, U, ME, yeah...

Python can't determine whether a reference is callable until it has resolved
it. What's happening in the first case is that it's calling
k.__getattr__('func1') followed by k.__getattr__('func2'), then calls the
second result, then passes the returned value to the first result.

In the second case, well, it doesn't return what you wrote above for me. It
returns "k.func2()", "k.func3()", "k.func3(24)". This is explainable as above,
so you might want to double-check your output.

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>





More information about the Python-list mailing list