Dynamically Defined Functions in Classes?
Wolfgang Grafen
wolfgang.grafen at marconi.com
Thu Feb 1 04:42:45 EST 2001
Pieter Nagel wrote:
>
> On Wed, 31 Jan 2001, Jim Meyer wrote:
>
> > I have an application in which I wish to treat the members of a
> > dictionary as attributes;
>
> class Bar:
> def __init__(self, initial_dict):
> self.__dict__ = initial_dict
>
> b = Bar({'joe' : 'cool', 'frank' : 'lee', 'ron' : 'dell'})
> print b.joe
> b.frank = 'foo'
>
> --
> ,_
> /_) /| /
> / i e t e r / |/ a g e l
Good idea!
Let's do a little additional stuff and you get:
class Bar(UserDict):
def __init__(self,dict={}):
UserDict.__init__(self,dict)
self.data.update(self.__dict__)
self.__dict__=self.data
>>> b=Bar({'a':1,'b':2)
>>> b
{'data': {...}, 'b': 2, 'a': 1}
>>> b.b
2
>>> b.a
1
>>> b['c']=3
>>> b
{'data': {...}, 'b': 2, 'c': 3, 'a': 1}
>>> b.c
3
>>> b['b']
2
Cheers,
Wolfgang
More information about the Python-list
mailing list