Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过对象字符串表示而不是对象来访问字典中的键_Python_Dictionary - Fatal编程技术网

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

Python 通过对象字符串表示而不是对象来访问字典中的键,python,dictionary,Python,Dictionary,我有一个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')

我有一个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上提供两个访问选项(键=对象/字符串)不是有一种更优雅的方法吗?比如重写dictionary类并提供其他方法或编写一些排序包装函数?解决这个问题的好方法是什么


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

将您的对象设置为
str
的子类就可以了。您的标签将成为对象的基础值,而不是对象的字段。感谢您的提示。不幸的是,
MyClass
已经从另一个基类派生,无法更改:(将对象设置为
str
的子类将完成此任务。标签将成为对象的基础值,而不是对象的字段。感谢您的提示。不幸的是,
MyClass
已派生自另一个基类,无法更改:(