[Tutor] __getattr__(): Is this right? [w/ new code]

Allen Fowler allen.fowler at yahoo.com
Tue Oct 16 06:01:55 CEST 2007


Umm... well. obviously I left out an __setattr__() call..

sigh.  

thanks anyway...

Allen Fowler <allen.fowler at yahoo.com> wrote: 


What did you try? What happened? What did you expect?

Kent

Narrowed things down a bit.....

Given this class:
-------------------------------
class sc(object):


    def __init__(self, **kargs):

        self.valid_props =  [ 'foo', 'bar', 'baz' ]

        for prop in self.valid_props:
            if kargs.has_key(prop):
                self.__setattr__(prop, kargs[prop])

    def  __getattr__(self,attr):
        if attr in self.valid_props:
            print "__getattr__ was called for %s" % attr
            return 'n/a'
        else:
            raise AttributeError, attr

This is my in/output:
---------------------------------
In [1]: some_string_a = 'foo' 

In [2]: some_string_b = 'FOO' 

In [3]: s = sc( foo=some_string_b )

In [4]: s.foo
Out[4]: 'FOO'

In [5]: eval('s.' + some_string_a)
Out[5]: 'FOO'

In [6]: s.__getattr__(some_string_a)
__getattr__ was called for foo
Out[6]: 'n/a'

In [7]: s.__getattr__('foo')
__getattr__ was called for foo
Out[7]: 'n/a'

In [8]: s.bar
__getattr__ was called for bar
__getattr__ was called  for bar
Out[8]: 'n/a'

In [9]: s.__getattr__('bar')
__getattr__ was called for bar
Out[9]: 'n/a'
    

Here is what I expected:
----------------------------------
Outputs 4 and 5 are fine.
Outputs 6 and 7 should have returned 'FOO'
Outputs 8 and 9 are fine. (But why two prints on 8?)

Thank you all.


        

---------------------------------
Don't let your dream ride pass you by.    Make it a reality with Yahoo! Autos.       _______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


       
---------------------------------
Moody friends. Drama queens. Your life? Nope! - their life, your story.
 Play Sims Stories at Yahoo! Games. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071015/12177555/attachment.htm 


More information about the Tutor mailing list