简体   繁体   English

如何创建一个用方括号调用的方法?

[英]How can I make a method that is called with square brackets?

1. What I need 1. 我需要什么

I have a Python class called List which has a list named mylist as attribute.我有一个名为List的 Python 类,它有一个名为mylist的列表作为属性。

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__ .现在我想创建一个名为slice的方法,它具有__getitem____setitem__的相同属性。 That is, call the method using Python slice syntax for getting and setting values to mylist attribute.也就是说,使用 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

I think that this method should have the same logic as DataFrame().iloc[] from Pandas.我认为这个方法应该与DataFrame().iloc[]具有相同的逻辑。

2. What I've tried 2. 我试过的

I tried to use the @property decorator, but I still don't really understand how to use it to solve this problem.我尝试使用@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]

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

Just return the mylist in the property只需返回属性中的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])

Output输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能将数字打印为列表的元素而不用引号和方括号呢? - How can I print the number as elements of a list without the quotes and square brackets should be their? 如何通过Spark / Pyspark中的saveAsTextFile保存不带方括号的列表 - How can I save lists without square brackets via saveAsTextFile in Spark/Pyspark 我可以在 python 中使用方括号来输入可枚举的提示吗? - Can I use square brackets in python to type hint enumerable? 如何使输入接受括号中的任何形式的单词? - How can I make the input accept any form of the words in the brackets? 如何删除 JSON 上的方括号,以便它可以在 Python 中的 Dataframe 中转换 - How to remove square brackets on a JSON so it can be converted in a Dataframe in Python 如何用零填充参差不齐的张量以制作方形张量 - How can I fill a ragged tensor with zeros to make a square tensor 如何在 Python 中创建递归平方根? - How can I make a recursive square root in Python? 如何操纵跟踪器区域使其变成方形? - How can I manipulate the tracker area to make it into a square shape? 当点进入正方形时,如何使点变色? - how can i make dots change color when they enter a square 如何制作具有指定周长的正方形并添加边距? - How can I make a square with a specified circumference and add margin?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM