Using inner dict as class interface

F

Florian Lindner

Hello,

I have a:

class C:
def __init__(self):
d = dict_like_object_created_somewhere_else()

def some_other_methods(self):
pass


class C should behave like a it was the dict d. So I could do:

c = C()
print c["key"]
print len(c)

but also

c.some_other_method()

How can I achieve that? Do I need to define all methods like
__getitem__, __len__, ... (what else?) to access the inner dict or is
there something more slick?

Thanks,

Florian
 
S

Steven D'Aprano

Hello,

I have a:

class C:
def __init__(self):
d = dict_like_object_created_somewhere_else()

def some_other_methods(self):
pass


class C should behave like a it was the dict d.

Then make it a dict:

class C(dict):
def some_other_methods(self):
pass

my_dict = C(key="value") # or C({"key": "value"})
print len(my_dict)
print my_dict['key']
my_dict.some_other_methods()
 
P

Peter Otten

Steven said:
Hello,

I have a:

class C:
def __init__(self):
d = dict_like_object_created_somewhere_else()

def some_other_methods(self):
pass


class C should behave like a it was the dict d.

Then make it a dict:

class C(dict):
def some_other_methods(self):
pass

my_dict = C(key="value") # or C({"key": "value"})
print len(my_dict)
print my_dict['key']
my_dict.some_other_methods()

If for some reason it is impractical to follow Steven's advice you can
subclass collections.Mapping or collections.MutableMapping. That should give
you a clear notion of the required methods and has defaults for some of
them.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class A with abstract methods
__getitem__, __iter__, __len__.... def __getitem__(self, key):
.... return {1:2}[key]
.... def __len__(self): return 1
.... def __iter__(self): yield 1
....
[(1, 2)]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top