<p>对象在Python中没有名称,可以为同一对象指定多个名称。</p>
<p>然而,一种面向对象的方法是对内置的<code>dict</code>字典类进行子类化并向其添加<code>name</code>属性。它的实例的行为与普通词典完全一样,几乎可以在任何正常词典可以使用的地方使用。</p>
<pre><code>class NamedDict(dict):
def __init__(self, *args, **kwargs):
try:
self._name = kwargs.pop('name')
except KeyError:
raise KeyError('a "name" keyword argument must be supplied')
super(NamedDict, self).__init__(*args, **kwargs)
@classmethod
def fromkeys(cls, name, seq, value=None):
return cls(dict.fromkeys(seq, value), name=name)
@property
def name(self):
return self._name
dict_list = [NamedDict.fromkeys('dict1', range(1,4)),
NamedDict.fromkeys('dicta', range(1,4), 'a'),
NamedDict.fromkeys('dict666', range(1,4), 666)]
for dc in dict_list:
print 'the name of the dictionary is ', dc.name
print 'the dictionary looks like ', dc
</code></pre>
<p>输出:</p>
<pre class="lang-none prettyprint-override"><code>the name of the dictionary is dict1
the dictionary looks like {1: None, 2: None, 3: None}
the name of the dictionary is dicta
the dictionary looks like {1: 'a', 2: 'a', 3: 'a'}
the name of the dictionary is dict666
the dictionary looks like {1: 666, 2: 666, 3: 666}
</code></pre>