python - Using 'self' with a square bracket -
i wondering whether or not can utilize square bracket self[avariable]
, have implemented __getitem__
. code have tried:
class myclass: def __getitem__(self,index): homecoming self[index] babe = myclass() print babe[4]
when run shows:
file "c:/python27/df", line 3, in __getitem__ homecoming self[index]
recursively.
how can utilize variable self[name]
__getitem__
in python?
your class needs have index, rather self
. example, in class foo
, has fellow member variable data
list. index operation index out of list data
example.
class foo(): def __init__(self, l): self.data = l def __getitem__(self, index): homecoming self.data[index] >>> = foo([1,2,3]) >>> a[1] 2
python
No comments:
Post a Comment