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

如何通过字符串设置Dart类属性?求类似Python __setattr__的实现

在Dart中实现类似Python getattr/__setattr__的动态属性功能

要实现你想要的动态读写任意属性的效果,Dart里可以通过重写noSuchMethod方法来拦截不存在的属性访问和赋值,这就对应Python里的__getattr__和__setattr__。下面是完全符合你需求的代码实现:

import 'dart:mirrors';

class MyClass {
  final Map<String, dynamic> _data = {};

  @override
  dynamic noSuchMethod(Invocation invocation) {
    // 处理属性读取操作(对应Python的__getattr__)
    if (invocation.isGetter) {
      final propName = MirrorSystem.getName(invocation.memberName);
      return _data[propName] ?? null;
    }

    // 处理属性赋值操作(对应Python的__setattr__)
    if (invocation.isSetter) {
      // Setter的成员名会带后缀=,需要去掉
      final propName = MirrorSystem.getName(invocation.memberName).replaceFirst('=', '');
      final value = invocation.positionalArguments.first;
      _data[propName] = value;
      return null;
    }

    // 其他未知调用,交给父类处理
    return super.noSuchMethod(invocation);
  }
}

void main() {
  MyClass mc = MyClass();
  print(mc.anything123);  // 输出 null
  mc.anything123 = 'some value';
  print(mc.anything123);  // 输出 'some value'
}

关键说明:

  • 必须导入dart:mirrors库才能使用MirrorSystem获取属性名称
  • noSuchMethod是Dart的特殊方法,当代码访问类中未定义的属性/方法时会自动触发
  • 通过invocation.isGetter和invocation.isSetter区分是读还是写操作
  • 用内部的_dataMap来存储所有动态添加的属性键值对

你之前代码的问题:

你之前写的get(String propertyName)是普通方法,Dart不会自动把mc.anything123这种属性访问语法转换成调用get('anything123'),必须通过noSuchMethod拦截这类动态访问行为才能实现类似Python的效果。

内容的提问来源于stack exchange,提问作者Daniel Olson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:12:55