Python自定义字典子类如何在alfa方法内获取当前调用的key值
核心问题分析
你现有代码的__getitem__方法返回的是整个Dictn实例本身,不管访问哪个key返回的都是同一个字典对象,所以alfa/beta方法根本无法感知到当前调用对应的key是什么。
解决方案
我们可以新增一个绑定key的代理类,__getitem__访问key的时候返回这个代理实例,代理类中会携带当前key和字典实例的引用,这样方法内部就能直接拿到对应的key了,完全适配你现有dict['key'].alfa()的调用习惯:
from dataclasses import dataclass class Dictn(dict): def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.__dict__ = self def __getitem__(self, key): # 不存在对应key时初始化默认的dataclass实例,可根据你业务需求修改 if key not in self: self[key] = DictnValue() # 返回绑定了当前key和字典的代理对象 return KeyProxy(self, key) # 你要操作的dataclass定义,可自定义字段 @dataclass class DictnValue: es: int = 0 te: int = 0 class KeyProxy: def __init__(self, dict_obj: Dictn, key: str): self.dict_obj = dict_obj self.current_key = key # 此处即可拿到当前调用对应的key self.current_value = dict_obj[key] def alfa(self, **kwds): # 给对应dataclass设置属性 for attr_name, attr_val in kwds.items(): setattr(self.current_value, attr_name, attr_val) def beta(self, **kwds): # 逻辑和alfa一致,可根据业务需求修改 for attr_name, attr_val in kwds.items(): setattr(self.current_value, attr_name, attr_val) # 测试运行 dictn = Dictn() dictn['ABC'].alfa(es=1, te=2) print(dictn['ABC']) # 输出 DictnValue(es=1, te=2) dictn['ABC'].beta(es=3, te=4) print(dictn['ABC']) # 输出 DictnValue(es=3, te=4)
可选简化方案
如果你不需要严格保留原有调用格式,也可以直接把key作为参数传给alfa方法,不需要额外代理类,实现更简单:
from dataclasses import dataclass @dataclass class DictnValue: es:int=0 te:int=0 class Dictn(dict): def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.__dict__ = self def alfa(self, key, **kwds): if key not in self: self[key] = DictnValue() for attr_name, attr_val in kwds.items(): setattr(self[key], attr_name, attr_val) def beta(self, key, **kwds): if key not in self: self[key] = DictnValue() for attr_name, attr_val in kwds.items(): setattr(self[key], attr_name, attr_val) # 调用方式 dictn = Dictn() dictn.alfa('ABC', es=1, te=2) dictn.beta('ABC', es=3, te=4)
内容的提问来源于stack exchange,提问作者misantroop
相关产品推荐
相关产品推荐

