I use a 'SuperDict' all the time in my code. Not sure it's a good idea, but I find it convenient. Also, I wouldn't mind comments on why/why not to use something like this:
class SuperDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value def set_with_dict(self,D): """ set attributes with a dict """ for k in D.keys(): self.__setattr__(k,D[k]) Here's the original thread (NOTE: I have also been trying to use more structured arrays as recommended by one poster): http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-this-one-may-take-some-thought--%29-td23759398.html On Tue, Oct 27, 2009 at 1:45 PM, Christian Witts <cwi...@compuscan.co.za>wrote: > Modulok wrote: > >> List, >> >> I'm new to the list, (somewhat new to python too). My code feels >> hacky. I'd like to know if there is a more eloquent way (more below). >> If not, a general thumbs up from more experienced programmers would be >> great! >> >> Assume I have a dict, 'foo'. I also have my own class, 'Bar', which >> subclasses (i.e. is a derived class) of a dict. How do I eloquently >> get foo into an instace of Bar? Example: >> >> >> ### BEGIN CODE: >> class Bar(dict): >> pass # Act like a dict for now. >> >> foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return >> value. >> myvar = Bar() >> # The hacky feeling part: >> for k,v in foo.items(): myvar[k] = v >> >> ### END CODE >> >> Obviously I can put the dict into an instance variable, but then >> methods like 'keys()' and such won't work. If that makes any sense... >> >> Thanks guys! >> -Modulok- >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > You can use the built-in function for dictionaries called update. So > > >>> class Bar(dict): > >>> pass > > > >>> foo = {'a':100, 'b':200, 'c': 300} > >>> myvar = Bar() > >>> myvar.update(foo) > >>> myvar > {'a': 100, 'c': 300, 'b': 200} > > -- > Kind Regards, > Christian Witts > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor