The operator.itemgetter() function works like this:
>>> import operator
>>> getseconditem = operator.itemgetter(1)
>>> ls = ['a', 'b', 'c', 'd']
>>> getseconditem(ls)
'b'
EDIT I’ve added this portion to highlight the inconsitency
>>> def myitemgetter(item):
... def g(obj):
... return obj[item]
... return g
>>> mygetseconditem = myitemgetter(1)
Now, I have this class
>>> class Items(object):
... second = getseconditem
... mysecond = mygetseconditem
...
... def __init__(self, *items):
... self.items = items
...
... def __getitem__(self, i):
... return self.items[i]
Accessing the second item with its index works
>>> obj = Items('a', 'b', 'c', 'd')
>>> obj[1]
>>> 'b'
And so does accessing it via the mysecond method
>>> obj.mysecond()
'b'
But for some reason, using the second() method raises an exception
>>> obj.second()
TypeError: itemgetter expected 1 arguments, got 0
What gives?
obj.secondis the functiongetseconditem. A function which expects an argument to operate on. Since you callobj.secondwithout any arguments the error you gave is raised. To solve it you can doobj.second(obj.items)or defineseconddifferently:Edit
It’s clear what you mean now after you edited your question. I think what’s going on here is that because
getseconditemis not a user-defined function it does not get transformed to a method upon accessingobj.second. It simply stays a function. The following can be found in thedocs: