You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Dart中能否定义类似Python __getitem__的元素获取方法?

在Dart中实现类似Python __getitem__的元素获取器

Dart里没有__getitem__这类特殊方法,但可以通过重载operator[]运算符实现相同效果,让类实例能像列表一样通过索引直接获取元素。

修改你的代码如下:

class ClassHoldingList {
  ClassHoldingList({required this.listAttribute});

  final List<int> listAttribute; // 建议用final保证属性不可变性,不需要可变时可保留原写法

  // 重载[]运算符,实现索引访问
  int operator [](int index) => listAttribute[index];
}

void main() {
  final instance = ClassHoldingList(listAttribute: [1, 2, 3, 4]);
  print(instance[1]); // 输出: 2
}

额外补充

如果需要支持通过索引设置元素(类似Python的__setitem__),可以同时重载operator[]=:

void operator []=(int index, int value) => listAttribute[index] = value;

使用示例:

instance[1] = 5;
print(instance[1]); // 输出: 5

内容的提问来源于stack exchange,提问作者Pierre Massé

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:24:53