Home > other >  How can I make a method that is called with square brackets?
How can I make a method that is called with square brackets?

Time:10-16

1. What I need

I have a Python class called List which has a list named mylist as attribute.

class List:
    def __init__(self):
        self.mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Now I want to make a method named slice that has the same properties of __getitem__ and __setitem__. That is, call the method using Python slice syntax for getting and setting values to mylist attribute.

l = List()
l.slice[2:6] # returns [3, 4, 5, 6]
l.slice[-1]  # returns 9
l.slice[1] = 10 # change the value in position 1 of my list to 10
l.slice[-1] = 10 # change value in the last position of my list to 10

I think that this method should have the same logic as DataFrame().iloc[] from Pandas.

2. What I've tried

I tried to use the @property decorator, but I still don't really understand how to use it to solve this problem.

class List:
    def __init__(self):
        self.mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    @property
    def slice(self):
        return self._mylist 
    
    @slice.__getitem__
    def iloc(self, mini, maxi):
        self._mylist = self.mylist[mini, maxi]

But this returns me the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1592/4117693097.py in <module>
----> 1 class List:
      2     def __init__(self):
      3         self.mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
      4 
      5     @property

~\AppData\Local\Temp/ipykernel_1592/4117693097.py in List()
      7         return self._mylist
      8 
----> 9     @slice.__getitem__
     10     def iloc(self, mini, maxi):
     11         self._mylist = self.mylist[mini, maxi]

AttributeError: 'property' object has no attribute '__getitem__'

CodePudding user response:

Just return the mylist in the property

class List:
    def __init__(self):
        self.mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

    @property
    def slice(self):
        return self.mylist


l = List()
print(l.slice[2:6])
print(l.slice[-1])  
l.slice[1] = 10
print(l.mylist[1])
l.slice[-1] = 10
print(l.mylist[-1])

Output

[3, 4, 5, 6]
9
10
10
  • Related