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 6 3554
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
"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.)
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
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
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.
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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,...
|
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__
|
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...
|
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
|
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...
|
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...
|
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__ =...
|
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
.... ...
|
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...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: MeoLessi9 |
last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
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...
|
by: marcoviolo |
last post by:
Dear all,
I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
|
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...
|
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...
| |