在Python中,我可以通过重写__getitem__
来使任何类支持索引:
class Test:
def __getitem__(self, key):
return self.data[key]
Dart是否有类似的构造?
答案 0 :(得分:8)
假设__getitem__
允许您使用“索引”语法(object[index]
),是的,Dart允许您通过定义operator []
来执行相同操作。例如:
class Test {
var data = {
"a": 1,
"b": 2
};
operator [](index) => data[index];
}
main() {
var t = new Test();
print(t["a"]);
print(t["b"]);
}
您还可以定义“对面”operator []=
:
class Test {
Map data = {
"a": 1,
"b": 2
};
operator [](index) => data[index];
operator []=(index, value) { data[index] = value; }
}
main() {
var t = new Test();
print(t["a"]);
print(t["b"]);
t["c"] = 3;
print(t["c"]);
}