UserDict and setattr

Chad Everett chat at linuxsupreme.homeip.net
Tue Jun 26 19:56:55 CEST 2001


Using UserDict and overriding getattr, I can create dictionary wrappers
that allow dictionary lookups via getattr.  Using the example below:

apple = Fruit( {'name':"apple",'color':'red'} )
carrot = Veggie( {'name':"carrot",'color':'orange'} )

apple.color         # returns 'red'
apple['color']      # returns 'red'

apple['color'] = 'green'
apple.color         # returns 'green'
apple['color']      # returns 'green'

apple.color = 'brown'
apple.color         # returns 'brown'
apple['color']      # returns 'green"  !!!!!!!!!

Obviously, setattr needs to be altered to also update
the dictionary (via __setitem__) and not just the instance's 
attributes

I cannot seem to find a way to override setattr so that I 
can get the get a __setitem__ called to update the dictionary.

Please Help!!!


Code sample follows:


import UserDict

class DictWrap(UserDict.UserDict):

    def __init__(self,initdict):
        self.data = initdict
        
    def __getattr__(self,name):
        return self.data[name]


class Fruit(DictWrap):


    def __init__(self,initdict):
        DictWrap.__init__(self,initdict)


class Veggie(DictWrap):


    def __init__(self,initdict):
        DictWrap.__init__(self,initdict)


apple = Fruit({'name':"apple",'color':'red'})
carrot = Veggie({'name':"carrot",'color':'orange'})





-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----



More information about the Python-list mailing list