TIMEX
TIMEX

Reputation: 271724

How do I properly subclass a "dict"?

class MyDict(dict):
    def __init__(self, *args):
        #fill in here

How do I write the constructor so that it sets the key 'name' to 'james'.

d = MyDict()
print d['name'] ....this should print out "james"

Upvotes: 0

Views: 203

Answers (2)

cwallenpoole
cwallenpoole

Reputation: 81998

A basic subclass of dict will allow basic storage:

class MyDict(dict):
    def __init__(self, *args):
        super(MyDict, self).__init__(*args, **kwargs)
        self['name'] = 'james'

For more complicated storage, you may want to look into __setitem__ and __getitem__

Upvotes: 0

wberry
wberry

Reputation: 19347

In (C)Python 2.5.2:

>>> class MyDict(dict):
...   def __init__(self, *args, **kwargs):
...     super(MyDict, self).__init__(*args, **kwargs)
...     self['name'] = 'james'
...
>>> d = MyDict()
>>> print d['name']
james

Upvotes: 2

Related Questions