python - 如何制作一个用方括号调用的方法?
问题描述
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__'
解决方案
只需返回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
推荐阅读
- regex - 正则表达式模式版本和名称
- html - 为什么 *ngFor 不以正确的顺序显示 html 表格行?
- javascript - 默认情况下如何隐藏 Node.js 中的内部堆栈跟踪错误?
- python - Django中自定义用户模型的用户权限
- ruby-on-rails - 在一对多 Rails ActiveRecord 关系中,获取只有子记录的父记录的最佳实践是什么?
- pattern-matching - 无法在 elixir-lang 的案例指南中使用第一个示例
- angular - 防止 Angular Capacitor Ionic 应用程序中的后退导航
- neo4j - Neo4J cypher:收集中间节点属性(路径)
- r - 确定一个值是否被 R 中的组重复
- jquery - 提交表单 e.preventDefault() 后如何运行一些脚本并继续进行 html5 验证?