我想將一個對象表示爲一個字符串,以便它既可以作爲字典鍵也可以作爲對象本身來訪問。即Python,將非字符串對象表示爲字符串?
class test(object):
def __init__(self, name, number_array):
self.name = name
self.number_array = number_array
self.graph= barChart(number_array)
sample_obj = test('test_object', [(x1,y1), (x2,y2)etc.])
但讓{sample_obj: another_object}
看起來像{'test_object': another_object}
,同時還使得這樣的可能:
for key, val in sample_dict.items(): print(key.name, key.graph)
還有:
>>> sample_dict['test_object']
another_object
目前沒有辦法提供這樣的關鍵別名,所以'dict'會將''test_object''視爲'some_object'的別名。參見[PEP-455](http://legacy.python.org/dev/peps/pep-0455/)提供了一個可以添加一個新類型的'dict'的提案。 – chepner 2014-09-25 13:22:25
是否可以更改訪問字典中對象的默認方法?因此,而不是說,D ['foo']檢查t .__ eq __('foo')是否檢查t.name .__ eq __('foo')?可以覆蓋__getitem__嗎? – user3467349 2014-09-25 13:38:17
Chepner錯了。有可能做你想做的事。 – haael 2014-09-25 13:54:26