By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,376 Members | 1,566 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,376 IT Pros & Developers. It's quick & easy.

Defining __getitem__() in a class that inherits from (dict)

P: n/a
#!/usr/bin/python

# Hi,
#
# I noticed something interesting when trying to define
# the __getitem__() method in a class that inherits from
# (dict). If within the __getitem__ method I attempt
# to get an item from self, the __getitem__ method is
# called in an infinite recursion. I am very fond of
# inheriting from (dict) as in the class 'bar' below,
# but this problem is making me think that I will have
# to write them as in 'foo' below. Is there a workaround
# to make the class 'bar' work as I planned?

class foo:

data = {}

def __getitem__(self, what):
if not self.data.has_key(what):
self.data[what] = None
return None
else:
return self.data[what]
class bar(dict):

data = {}

def __getitem__(self, what):
if not self.has_key(what):
self[what] = None
return None
else:
return self[what]
f = foo()
b = bar()
print f['somekey']
print f['somekey']

print b['somekey']
print b['somekey']
# OUTPUT:
# None
# None
# None
# Traceback (most recent call last):
# File "<stdin>", line 47, in ?
# File "<stdin>", line 36, in __getitem__
# File "<stdin>", line 36, in __getitem__
# File "<stdin>", line 36, in __getitem__

Thanks,

Tobiah
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Tobiah wrote:
If within the __getitem__ method I attempt
to get an item from self, the __getitem__ method is
called in an infinite recursion.


You need to explicitly use dict.__getitem__(self, key) instead of
using self[key] directly.
--
Michael Hoffman
Jul 18 '05 #2

P: n/a
Michael Hoffman wrote:
Tobiah wrote:
If within the __getitem__ method I attempt
to get an item from self, the __getitem__ method is
called in an infinite recursion.


You need to explicitly use dict.__getitem__(self, key) instead of
using self[key] directly.


or super(bar, self).__getitem__(key)

STeVe
Jul 18 '05 #3

P: n/a
My appreciation for your responses is not
easily imparted through text. Thank You.

Steven Bethard wrote:
Michael Hoffman wrote:
Tobiah wrote:
If within the __getitem__ method I attempt
to get an item from self, the __getitem__ method is
called in an infinite recursion.

You need to explicitly use dict.__getitem__(self, key) instead of
using self[key] directly.

or super(bar, self).__getitem__(key)

STeVe

Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.