473,804 Members | 3,433 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3589
it seems like you can't do it exactly the way you're trying but you could do
this

def __getitem__(*ar gs):
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.atw rote in message
news:uf******** ****@buckbeak.h ogwarts...
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.c omwrote in message
news:Ly******** ***********@big news3.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__(*ar gs):
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.atw rote in message
news:uf******** ****@buckbeak.h ogwarts...
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.co m 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__(*ar gs):
Apparently, args already is a tuple, so this should be:

def __getitem__(sel f, 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__(sel f, 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.ate scribió:
in****@gmail.co m 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__(*ar gs):

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

def __getitem__(sel f, 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
8027
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
2062
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
2046
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 inheritance and operator overloading (both concepts that I initially found hard to grasp). I've written a simple config file parser - and I thought I'd experiment with making the interface easier by subclassing dict and overloading the __setitem__,...
33
2542
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
4039
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 an instance of this class, then x is equivalent to x.__getitem__(i)" Consider the following code:
3
5959
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 # 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,
1
1986
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
3588
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()
3
2074
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 "NStr:getitem",idx,type(idx) return str.__getitem__(self,idx) s=NStr("abcde")
0
9706
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
9579
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,...
0
10575
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10319
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
10076
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6851
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
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3816
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.