python use __getitem__ for a method
is it possible to use getitem inside a method, ie
Class MyClass:
@property
def function(self):
def __getitem__():
...
开发者_C百科
So I can do
A = MyClass()
A.function[5]
A.function[-1]
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'
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.
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?
精彩评论