Overloading __getitem__
inhahe
inhahe at gmail.com
Thu May 22 18:36:15 EDT 2008
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" <amat at kabsi.at> wrote in message
news:uf6hg5-ca9.ln1 at 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
More information about the Python-list
mailing list