对于模糊的标题,我不太确定该怎么说:
假设我们有一个类,它包含嵌入在更大的字典中的字典。
class AnObject(object):
grail = {'Grail' : '', 'Quest' : ''}
spam = {'More spam' : '', 'Less spam' : ''}
parrot = {'More parrot' : '', 'Less parrot' : '', 'Grail' : grail}
egg = {'Spam' : spam, 'Parrot' : parrot }
然后我们想用其他名称来调用这些属性
self.egg = egg
self.parrot = egg['Parrot']
self.moreparrot = self.parrot['More parrot']
这会带来正确的位置,但由于某种原因,我找到了......
>>>knight = AnObject()
>>>knight.moreparrot = x
>>>knight.moreparrot
x
>>>knight.egg
{'Parrot' : {'More parrot' : '', 'Less parrot' : ''}...}
但这很好用:
>>>knight.egg['Parrot']['More parrot'] = x
>>>knight.egg['Parrot']['More parrot']
x
>>>knight.egg
{'Parrot' : {'More parrot' : '', 'Less parrot' : ''}...}
这些应该指向相同的变量,但我得到的结果不同。怎么样?
编辑:
这可能完全是偶然的,但由于某些原因垃圾邮件是一致的。
self.egg = egg
self.spam = egg['Spam']
self.morespam = self.spam['More spam']
>>>knight = AnObject()
>>>knight.morespam = x
>>>knight.morespam
x
>>>knight.egg['Spam']['More spam']
x
>>>knight.egg
{'Spam' : {'More spam' : 'x', 'Less spam' : ''}...}