473,793 Members | 2,742 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

#!/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__(sel f, what):
if not self.data.has_k ey(what):
self.data[what] = None
return None
else:
return self.data[what]
class bar(dict):

data = {}

def __getitem__(sel f, what):
if not self.has_key(wh at):
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
3 5957
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
8026
by: KanZen | last post by:
I'm trying to understand the difference between __setitem__ and an ordinary method. For example: >>> class A(object): def __getitem__(self, *args): print len(args) def normalMethod(self, *args): print len(args) >>> a=A()
1
1985
by: simon | last post by:
What i'm trying to do is tie special methods of a "proxy" instance to another instance: def test1(): class Container: def __init__( self, data ): self.data = data self.__getitem__ = self.data.__getitem__ data = range(10)
21
3584
by: ron | last post by:
Why doesn't this work? >>> def foo(lst): .... class baz(object): .... def __getitem__(cls, idx): return cls.lst .... __getitem__=classmethod(__getitem__) .... baz.lst = lst .... return baz .... >>> f = foo()
7
2335
by: David Isaac | last post by:
I have a subclass of dict where __getitem__ returns None rather than raising KeyError for missing keys. (The why of that is not important for this question.) I was delighted to find that __contains__ still works as before after overriding __getitem__. So even though instance does not raise KeyError, I still get (as desired) 'key' in instance == False. Looking forward:
0
2838
by: emin.shopper | last post by:
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass magic, I wrote the following module. It is mainly useful as a light weight tool to help programmers catch mistakes at definition time (e.g., forgetting to implement a method required by the given interface). This is handy when unit tests or...
0
1046
by: dackz | last post by:
>>class ListyThing(list): pass .... Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError <type 'list'> I don't find this intuitive. Is this intentional? I believe this could be avoided if list.__getitem__ used "self.__class__()" to make a new instance, instead of "list()", but I don't know how that works under
9
3083
by: nik | last post by:
Hi, I would like to create a class and then save it for re-use later. I have tried to use pickle, but am not sure if that is right. I am sorry, but I am new to python. Basically, I have a class, Map. I want to be able to create new maps: MapA, MapB... that have Map as the base class. start with-
6
3586
by: Andreas Matthias | last post by:
The following code doesn't run but I hope you get what I am trying to do. class my_dict (dict): def __getitem__ (self, key, crazy = False): if crazy == True: return 5 * self.get(key) else:
5
4483
by: Bojan Mihelac | last post by:
Hi all - when trying to set some dynamic attributes in class, for example: class A: for lang in : exec('title_%s = lang' % lang) #this work but is ugly # setattr(A, "title_%s" % lang, lang) # this wont work setattr(A, "title_1", "x") # this work when outside class
0
9671
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6777
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.