【问题标题】:How can I make a method that is called with square brackets?如何制作一个用方括号调用的方法?
【发布时间】:2021-12-03 21:52:59
【问题描述】:

1。我需要什么

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

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

现在我想创建一个名为slice 的方法,它具有__getitem____setitem__ 的相同属性。即,使用 Python 切片语法调用该方法,以获取和设置 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

我觉得这个方法应该和 Pandas 的DataFrame().iloc[] 有同样的逻辑。

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

【问题讨论】:

  • 删除 @iloc.__getitem__ 之后的所有内容,包括在内。在实际的property 中返回的self._mylist 已经做了你想要的。
  • 嗯......但我想它需要被问......为什么不从list本身继承,即就像class List(list) 一样,我猜在这种情况下访问切片而不使用slice 方法?
  • 这在这个例子中可以工作,但在我真正的问题中不会。我需要为我的数据库类创建一个选择表切片的方法。

标签: python python-3.x oop methods slice


【解决方案1】:

只需返回属性中的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

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多