Dictionaries and dot notation
Martin Drautzburg
Martin.Drautzburg at web.de
Mon Apr 23 02:14:32 EDT 2007
Alex Martelli wrote:
> Martin Drautzburg <Martin.Drautzburg at web.de> wrote:
>
>> > mydata = data( )
>> > mydata.foo = 'foo'
>> > mydata.bar = 'bar'
>> >
>> > print mydata.foo
>> > print mydata.bar
>>
>> I am aware of all this.
>> Okay let me rephrase my question: is there a way of using dot
>> notation without having to create a class?
>
> Sure, all you need to create is an *INSTANCE* of a suitable type or
> class. For example:
>
>>>> d = dict(foo=23, bar=45)
>>>> m = new.module('for_martin')
>>>> m.__dict__.update(d)
>>>> m.foo
> 23
>>>> m.bar
> 45
>>>>
>
> A module may be appropriate, since it's little more than a "wrapper
> around a dict to access items by dot notation":-).
Thanks, I finally got it. Even your previous example actually does the
trick. I did not notice that I can use a single class (or a module) for
all my datastructures, because I can "plug in" new attributes into the
instance without the class knowing about them.
I was mistaken to believe that I had to know about attributes at the
time of class creation. But your expample does not require that. Should
have read this more carefully.
More information about the Python-list
mailing list