首页 > 解决方案 > 如何制作一个用方括号调用的方法?

问题描述

1. 我需要什么

我有一个名为的 Python 类List,它有一个名为mylist属性的列表。

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

现在我想创建一个名为的方法,它具有与和slice相同的属性。也就是说,使用 Python 切片语法调用该方法以获取和设置属性值。__getitem____setitem__mylist

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

我认为这种方法应该与DataFrame().iloc[]Pandas 具有相同的逻辑。

2. 我试过的

我尝试使用@property装饰器,但我仍然不明白如何使用它来解决这个问题。

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]

但这会给我返回以下错误:

---------------------------------------------------------------------------
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__'

标签: pythonpython-3.xoopmethodsslice

解决方案


只需返回mylist属性

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])

输出

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

推荐阅读