tags:

views:

59

answers:

3

is it possible to use getitem inside a method, ie

Class MyClass:
    @property
    def function(self):
        def __getitem__():
            ...

So I can do

A = MyClass()
A.function[5]
A.function[-1]
+3  A: 

Everything is a first-class object in python, so the idea should work (the syntax is off), though I'd suggest making function its own class with properties in it, and then utilizing it in MyClass, unless you have a very good data-hiding reason to not do so...

I'd like to point out that I'm assuming you want to have function return a subscriptable thing, not have a subscriptable list of functions. That's a different implementation (also can be done, though.)

For example, a subscriptable thing (you could have made just a list, too):

# python

> class FooFunc(list):
>   pass
> class Foo:
>   foofunc = FooFunc()
> f = Foo()
> f.foofunc.append("bar")
> f.foofunc[0]
'bar'
eruciform
"should work"? Why guess? try it.
Ned Batchelder
@ned: i meant that the concept is fine, and neglected to say that the syntax was off. updated and with example.
eruciform
But in this case, the function itself doesn't contain the __getitem__ call. Here foofunc is a reference to a subclass of list.
McJeff
@mcjeff: i think that's what he was looking for. and it does have a \__getitem__ call -- within the list superclass... it's a little confusing if he wants a subscriptable list of functions or a property that is subscriptable...
eruciform
Yeah, the net syntax is the same, so that's probably fine. It's not a __getitem__ within a method, but eh, whatever. ;-)
McJeff
A: 

Nope, that will not work. Consider the underlying descriptor logic being called when you access an attribute that has been decorated as a @property. The get method needs to return a value that will be used as the computed property function. In this case, function doesn't return anything (implicit None value for the property). Your subscripting will then attempt to index None and boom.

You could return an object from function that supported the __getitem__ dunder method, though. That would syntactically "work" the same.

McJeff
A: 

If you try your code (after fixing the C in Class), you'll see it produces an error: "TypeError: 'NoneType' object is unsubscriptable".

I think your best bet is to create a class with a __getitem__, and set function to an instance of that class. Is there a reason it needs to be so complicated?

Ned Batchelder