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

Home Posts Topics Members FAQ

__getitem__ and arguments

I'm trying to understand the difference between __setitem__ and an
ordinary method. For example:
class A(object): def __getitem__(sel f, *args):
print len(args)
def normalMethod(se lf, *args):
print len(args)
a=A()
a.normalMethod( 1, 2, 3) 3 a[1, 2, 3]

1

For __getitem__() the arguments become a tuple. I can't seem to find
this in the language spec. Can anybody explain this to me?

Thanks,
KanZen.
Jul 18 '05 #1
4 8026
On 19 Jul 2003 02:10:25 -0700, KanZen wrote:
I'm trying to understand the difference between __setitem__ and an
ordinary method. For example:
(presuming you mean __getitem__)
class A(object): def __getitem__(sel f, *args):
print len(args)
def normalMethod(se lf, *args):
print len(args)
a=A()
a.normalMethod( 1, 2, 3) 3 a[1, 2, 3] 1


The dictionary access syntax you used specifies a key, which forces
everything between [] to become a single argument. In this case, it's a
tuple, (1, 2, 3).

Thus, the args for A.__getitem__() is a tuple of length one, containing
the specified key: the tuple (1, 2, 3). That is, args is a tuple
containing a tuple.

No such coercion occurs for function syntax; the difference is that you
didn't invoke __getitem__ with function syntax.
class A: .... def normal_method( self, *args ):
.... print len( args )
.... print type( args )
.... print args
.... def __getitem__( self, *args ):
.... print len( args )
.... print type( args )
.... print args
.... a = A()
a.normal_method ( 1, 2, 3 ) 3
<type 'tuple'>
(1, 2, 3) a[ 1, 2, 3 ] 1
<type 'tuple'>
((1, 2, 3),)

For __getitem__() the arguments become a tuple.


Yes, because you've specified a key, which by definition is a single
argument.

--
\ "He may look like an idiot and talk like an idiot but don't let |
`\ that fool you. He really is an idiot." -- Groucho Marx |
_o__) |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B
Jul 18 '05 #2
[KanZen]
class A(object): def __getitem__(sel f, *args):
print len(args)
a=A()
a[1, 2, 3]

1

For __getitem__() the arguments become a tuple. I can't seem to find this
in the language spec. Can anybody explain this to me?


Hello, KanZen.

When you write an argument list as `*args', you _always_ get a tuple
of all arguments. Normally, one writes:

def __getitem__(sel f, argument):
...

as `__getitem__' only accepts one argument besides `self'. Of course,
you may well write:

def __getitem__(sel f, *arguments):
...

but then, `arguments' will always be a 1-tuple in practice, and
`arguments[0]' will contain the actual argument.

This being said, consider the call `a[1, 2, 3]' (it does not look like a
call, but we both know that under the scene, this is calling `__getitem__').
We may be tempted to think that it works a bit the same as an explicit
function call would work, like if it was written `a(1, 2, 3)', and the
confusion might come from there. Indeed, in `a(1, 2, 3)', there are three
arguments. `a[1, 2, 3]' is not the same, it calls the `__getattr__' of `a'
with a _single_ argument `1, 2, 3'. That single argument is really a tuple
itself.

Many Python users like to write tuples as `(1, 2, 3)', using superfluous
parentheses for strange reasons. :-) They would likely write `a[(1, 2, 3)]'
as a way to over-stress that `a[]' accepts only one value within the
brackets. The writing `a[1, 2, 3]' is very legible because it is less
noisy, and you are right in preferring it. Yet you have to remember that
`1', `2' and `3' are not to become separate arguments for `__getitem__'.
The single argument will be what was within brackets, that is, a tuple.

--
François Pinard http://www.iro.umontreal.ca/~pinard

Jul 18 '05 #3
On Saturday 19 Jul 2003 10:10 am, KanZen wrote:
I'm trying to understand the difference between __setitem__ and an

ordinary method. For example:
class A(object):
def __getitem__(sel f, *args):
print len(args)
def normalMethod(se lf, *args):
print len(args)
a=A()
a.normalMethod( 1, 2, 3)
3
a[1, 2, 3]
1

For __getitem__() the arguments become a tuple. I can't seem to find
this in the language spec. Can anybody explain this to me?

Thanks,
KanZen.

Maybe the following will help:

-------------8<----------
class A(object): def __getitem__(sel f,*args):
print args
def test(self,*args ):
print args

a=A()
a[1] (1,) a[1:2] (slice(1, 2, None),) a.__getitem__(1 ) (1,) a.test(1) (1,)
-------------8<----------

This tells us what we could already guess from the formal parameter list:
*args returns a tuple of the arguments.

Try:

-------------8<---------- class A(object): def __getitem__(sel f,index):
print index
def test(self,index ):
print index

a=A()
a[1] 1 a[1:2] slice(1, 2, None) a.__getitem__(1 ) 1 a.test(1)

1
-------------8<----------

As you can see, both methods do the same. I think you're just seening the
effect of the variable arguments syntax.

I'm sure a Guru will correct me if I'm wrong, but I don't see evidence ofa
'special case' here... ;-)

hth
-andyj

Jul 18 '05 #4
On 20 Jul 2003 04:00:05 +0950, Ben Finney <bi************ ****@and-zip-does-too.com.au> wrote:
[...]
For __getitem__() the arguments become a tuple.


Yes, because you've specified a key, which by definition is a single
argument.

But note that it can be more than a simple tuple (or less, if it's an int):
class X(object): ... def __getitem__(sel f, i): print i
... x=X()
x[1] 1 x[1:] slice(1, None, None) x[:1] slice(None, 1, None) x[:] slice(None, None, None) x[1, :, 1:, :1, 1:2, 1:2:3, (4,5), 6]

(1, slice(None, None, None), slice(1, None, None), slice(None, 1, None), slice(1, 2, None),
slice(1, 2, 3), (4, 5), 6)

Notice that (4,5) in there also as one of the indices.

Regards,
Bengt Richter
Jul 18 '05 #5

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

Similar topics

0
1319
by: Karl Chen | last post by:
Hi. Is it possible to make a classmethod out of __getitem__? I.e. I want to do: class C: def __getitem__(p): return 1+p
7
2299
by: Steven Bethard | last post by:
So, GvR said a few times that he would like to get rid of lambda in Python 3000. Not to start up that war again, but I'm trying to eliminate unnecessary lambdas from my code, and I ran into a case using unittest.TestCase that I don't really know how to deal with. Previously, I had written some code like: self.assertRaises(ValueError, lambda: method(arg1, arg2)) This was a simple fix because assertRaises takes *args and **kwds, so
1
2134
by: Steve Juranich | last post by:
I'm in the process of writing a few extension types, and there's one that I'd sort of like to have getitem, setitem, getslice, setslice functionality for. I've been looking through the docs and how things are done in Objects/listobject.c, and it appears tha there are a couple of ways to do it and I'd like to get some opinions on what's the best way. As I see it, here are my options (please correct me if I'm wrong):
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
3587
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
2336
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:
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")
6
3589
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:
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
10326
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10317
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
9143
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...
0
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4295
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
3815
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.