__getatr__ question

Steve Holden sholden at holdenweb.com
Wed Oct 3 16:35:59 EDT 2001


"Jim" <jkring at calbay.com> wrote in message
news:89a9b6ce.0110030954.7ee3043f at posting.google.com...
> 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) + ')'

Well, what do you expect when you are trying to save state for a number of
recursive calls in the same instance variable. Try adding

    print "I just set 'self.string' to", a

inside the __getattr__() method. You will see that the setting of func1 is
overwritten by the setting of func2, because of the call structure.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list