473,320 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Overloading __getitem__

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:
return self.get(key)
foo = my_dict()
foo['a'] = 123

print foo['a']
print foo['a', crazy = True]
Is it somehow possible to overload __getitem__ with an additional
argument? Are there other possibilities to achiev this? Or is
the only solution to this to write a normal function call
`def my_get (self, key, crazy=False)'?
Ciao
Andreas
Jun 27 '08 #1
6 3555
it seems like you can't do it exactly the way you're trying but you could do
this

def __getitem__(*args):
if len(args) 1 and args[1]: return self.get(args[0]) * 5
return self.get(args[0])

then you would use it like

print foo['a']
print foo['a',True]
or even
print foo['a',"crazy"]
if you wanted.
or
crazy = True
print foo['a',crazy]


"Andreas Matthias" <am**@kabsi.atwrote in message
news:uf************@buckbeak.hogwarts...
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:
return self.get(key)
foo = my_dict()
foo['a'] = 123

print foo['a']
print foo['a', crazy = True]
Is it somehow possible to overload __getitem__ with an additional
argument? Are there other possibilities to achiev this? Or is
the only solution to this to write a normal function call
`def my_get (self, key, crazy=False)'?
Ciao
Andreas

Jun 27 '08 #2

"inhahe" <in****@gmail.comwrote in message
news:Ly*******************@bignews3.bellsouth.net. ..
crazy = True
print foo['a',crazy]
just to clarify, you could use it like:
crazy = "I'm crazy" #this only has to be done once

print foo['a'] #not crazy
print foo['a',crazy] #crazy

(this may be totally unPythonic, i don't know.)


Jun 27 '08 #3
actually i ddin't think about the fact that you're overloading dict, which
can already take multiple values in getitem

so how about

class crazy: pass

and then in your dict class:

def __getitem__(*args):
if args[-1] is crazy:
return self.get(args[:-1])*5
else:
return self.get(args)

and then
print foo[1,2] #not crazy
print foo[1,2,crazy] #crazy

I *think* that would work


"Andreas Matthias" <am**@kabsi.atwrote in message
news:uf************@buckbeak.hogwarts...
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:
return self.get(key)
foo = my_dict()
foo['a'] = 123

print foo['a']
print foo['a', crazy = True]
Is it somehow possible to overload __getitem__ with an additional
argument? Are there other possibilities to achiev this? Or is
the only solution to this to write a normal function call
`def my_get (self, key, crazy=False)'?
Ciao
Andreas

Jun 27 '08 #4
in****@gmail.com wrote:
actually i ddin't think about the fact that you're overloading dict, which
can already take multiple values in getitem
Oh, I didn't know that. I totally misinterpreted the error message.

so how about

class crazy: pass

and then in your dict class:

def __getitem__(*args):
Apparently, args already is a tuple, so this should be:

def __getitem__(self, args):

Is this documented somewhere? I couldn't find it anywhere.

Thanks.
Ciao
Andreas
Jun 27 '08 #5
Apparently, args already is a tuple, so this should be:

def __getitem__(self, args):

Is this documented somewhere? I couldn't find it anywhere.
Don't know, I just assumed it would take multiple arguments because I knew I
had seen the form d[1,2] before, which incidentally is equivalent to
d[(1,2)] so I guess it makes sense that args is a tuple.

Jun 27 '08 #6
En Thu, 22 May 2008 20:38:39 -0300, Andreas Matthias <am**@kabsi.atescribió:
in****@gmail.com wrote:
>actually i ddin't think about the fact that you're overloading dict, which
can already take multiple values in getitem

Oh, I didn't know that. I totally misinterpreted the error message.

>so how about

class crazy: pass

and then in your dict class:

def __getitem__(*args):

Apparently, args already is a tuple, so this should be:

def __getitem__(self, args):

Is this documented somewhere? I couldn't find it anywhere.
No, that's not correct. First, there is nothing special with the arguments to dict.__getitem__ -- except that the syntax obj[index] provides a delimiter and it allows for obj[a,b] as a shortcut for obj[(a,b)] -obj.__getitem__((a,b))

You may use the *args notation in any function; it is always a tuple (a singleton, when you call the function with only one argument)

pydef foo(*args): print args
....
pyfoo(1)
(1,)
pyfoo(1,2)
(1, 2)
pyfoo((1,2))
((1, 2),)

Compare with:

pydef bar(arg): print arg
....
pybar(1)
1
pybar(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes exactly 1 argument (2 given)
pybar((1,2))
(1, 2)

--
Gabriel Genellina

Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
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,...
1
by: Benoît Dejean | last post by:
class TargetWrapper(dict): def __init__(self, **kwargs): dict.__init__(self, kwargs) __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
1
by: Fuzzyman | last post by:
I've been programming in python for a few months now - and returning to programming after a gap of about ten years I've really enjoyed learning python. I've just made my first forays into...
33
by: Jacek Generowicz | last post by:
I would like to write a metaclass which would allow me to overload names in the definition of its instances, like this class Foo(object): __metaclass__ = OverloadingClass att = 1 att = 3
8
by: Sebastien Boisgerault | last post by:
I wonder if the following quotation from the Python Reference Manual (release 2.3.3) about operator overloading is true : "For example, if a class defines a method named __getitem__(), and x is...
3
by: Tobiah | last post by:
#!/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...
1
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__ =...
21
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 .... ...
3
by: tsm8015 | last post by:
I do not think I am understanding how to redefine the getitem function for string. Why does the following not work: class NStr(str): def __getitem__(self,idx): print...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.