Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python use __getitem__ for a method

Tags:

python

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]
like image 950
Austin Richardson Avatar asked Jul 16 '10 19:07

Austin Richardson


1 Answers

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'
like image 109
eruciform Avatar answered Sep 28 '22 09:09

eruciform