UserDict and setattr

Chad Everett chat at linuxsupreme.homeip.net
Tue Jun 26 15:58:55 EDT 2001


OK,  I just needed to add the following to DictWrap:

    def __setattr__(self,name,value):
        if name == "data":
            self.__dict__[name] = value
        else:
            self.__dict__['data'][name] = value


On 26 Jun 2001 12:56:55 -0500, Chad Everett <chat at linuxsupreme.homeip.net> wrote:
>
>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! =-----


-----= 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