Re: Getting a dictionary from an object
Thanos Tsouanas wrote:
I'm not sure what you're getting at, but have you tried this:
class A(object):
def __getitem__(sel f, ky):
return self.__dict__[ky]
for example:[color=blue][color=green][color=darkred]
>>> class A(object):[/color][/color][/color]
def __init__(self,a ,b,c):
self.a = a
self.b = b
self.c = c
def __getitem__(sel f, ky):
return self.__dict__[ky]
[color=blue][color=green][color=darkred]
>>> a = A(1,2,3)
>>> a['a'][/color][/color][/color]
1[color=blue][color=green][color=darkred]
>>> a['b'][/color][/color][/color]
2[color=blue][color=green][color=darkred]
>>>[/color][/color][/color]
[color=blue]
> Hello.
>
> I would like to have a quick way to create dicts from object, so that a
> call to foo['bar'] would return obj.bar.
>
> The following works, but I would prefer to use a built-in way if one
> exists. Is there one?
>
> Thanks in advance.
>
> class dictobj(dict):
> """
> class dictobj(dict):
> A dictionary d with an object attached to it,
> which treats d['foo'] as d.obj.foo.
> """
> def __init__(self, obj):
> self.obj = obj
> def __getitem__(sel f, key):
> return self.obj.__geta ttribute__(key)
>[/color]
Thanos Tsouanas wrote:
I'm not sure what you're getting at, but have you tried this:
class A(object):
def __getitem__(sel f, ky):
return self.__dict__[ky]
for example:[color=blue][color=green][color=darkred]
>>> class A(object):[/color][/color][/color]
def __init__(self,a ,b,c):
self.a = a
self.b = b
self.c = c
def __getitem__(sel f, ky):
return self.__dict__[ky]
[color=blue][color=green][color=darkred]
>>> a = A(1,2,3)
>>> a['a'][/color][/color][/color]
1[color=blue][color=green][color=darkred]
>>> a['b'][/color][/color][/color]
2[color=blue][color=green][color=darkred]
>>>[/color][/color][/color]
[color=blue]
> Hello.
>
> I would like to have a quick way to create dicts from object, so that a
> call to foo['bar'] would return obj.bar.
>
> The following works, but I would prefer to use a built-in way if one
> exists. Is there one?
>
> Thanks in advance.
>
> class dictobj(dict):
> """
> class dictobj(dict):
> A dictionary d with an object attached to it,
> which treats d['foo'] as d.obj.foo.
> """
> def __init__(self, obj):
> self.obj = obj
> def __getitem__(sel f, key):
> return self.obj.__geta ttribute__(key)
>[/color]
Comment