[Tutor] creating a dict-like class - asigning variables... this one may take some thought ; )

Lie Ryan lie.1296 at gmail.com
Fri Jul 3 14:21:28 CEST 2009


John [H2O] wrote:
> 
> 
> spir wrote:
>>
>> What you're looking for is a dictionary...
>> s = {"cheese":"Brie", "country":"France", ...}
>>
>> Or maybe a kind of object type that works ~ like a dict, but with object
>> syntax (get rid of {} and "" for keys). Example:
>>
>> class Stuff(object):
>> 	def __iter__(self):
>> 		return iter(self.__dict__.items())
>> 	def items(self):
>> 		return self.__dict__
>>
>> stuff = Stuff()
>> stuff.cheese="Brie"
>> stuff.country="France"
>> print stuff.cheese, stuff.country
>> print stuff.items()
>> for st in stuff:
>> 	print "   ", st
>> ==>
>> Brie France
>> {'cheese': 'Brie', 'country': 'France'}
>>     ('cheese', 'Brie')
>>     ('country', 'France')
>>
>>
>> Denis
>> ------
>> la vita e estrany
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> 
> 
> Denis,
> 
> This is working, but what would be ideal is to have 'best of both' worlds.
> Is there a way to combine this class with a dict, so that I can do both:

If you want to control attribute access, override its __getattr__ and
__setattr__.
If you want to make a dict lookalike, override its __getitem__ and
__setitem__ or inherit from dict.

Knowing this, you can do this:

class SuperDict(dict):
    def __getattr__(self, attr):
        return self[attr]
    def __setattr__(self, attr, value):
        self[attr] = value

>>> S = SuperDict()
>>> S.foo = 42
>>> S['bar'] = 100
>>> S.bar
100
>>> S['foo']
42
>>> S.items()
[('foo', 42), ('bar', 100)]

>>> S['this'] = 'is great'
>>> S.this
'is great'
>>> S.this = 'is even better'
>>> S['this']
'is even better'



More information about the Tutor mailing list