[英]How can I make a method that is called with square brackets?
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[]
具有相同的逻辑。
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.