![](/img/trans.png)
[英]How can I print the number as elements of a list without the quotes and square brackets should be their?
[英]How can I make a method that is called with square brackets?
我有一個名為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
我認為這個方法應該與DataFrame().iloc[]
具有相同的邏輯。
我嘗試使用@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__'
只需返回屬性中的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.