通过对象字符串表示而不是obj来访问字典中的键

2024-06-24 12:39:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python字典,它由特定类的对象元组设置键:

class MyClass:

    def __init__(self, label):
        self.label = label

    def __str__(self):
        return self.label

    def __repr__(self):
        return self.label

obj1 = MyClass('obj1')
obj2 = MyClass('obj2')
obj3 = MyClass('obj3')
obj4 = MyClass('obj4')

my_dict = {(obj1, obj2): 'foo', (obj3, obj4): 'bar'}

print(my_dict[(obj1, obj2)])

# this should also be possible (string API for dict): 
# print(my_dict[('obj1', 'obj2')])
# which works with the following code but seems to be not the best solution
my_dict2 = {tuple([str(e) for e in k]): v for k, v in my_dict.items()}
print(my_dict2[('obj1', 'obj2')])

现在我想通过使用带有对象字符串表示的键来访问元素,例如my_dict[('obj1', 'obj2'),我不确定如何以干净有效的方式解决这个问题

我的第一个很明显的想法是在另一个字典中将所有键转换成字符串,例如('obj1','obj2')

但是,在同一个dict上提供两个访问选项(keys=objects/strings)不是有一种更优雅的方法吗,比如重写dictionary类,提供额外的方法,或者编写一些排序包装函数?解决这个问题的好办法是什么

非常感谢您的帮助。提前谢谢


Tags: 对象selffor字典mydefmyclasslabel