Class 未指定给右变量的属性值
抱歉,标题含糊不清,我不太清楚该怎么说: 假设我们有一个类,它包含嵌入在较大词典中的词典Class 未指定给右变量的属性值,class,dictionary,attributes,python-3.6,Class,Dictionary,Attributes,Python 3.6,抱歉,标题含糊不清,我不太清楚该怎么说: 假设我们有一个类,它包含嵌入在较大词典中的词典 class AnObject(object): grail = {'Grail' : '', 'Quest' : ''} spam = {'More spam' : '', 'Less spam' : ''} parrot = {'More parrot' : '', 'Less parrot' : '', 'Grail' : grail} egg = {'Spam' :
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' : ''}...}
不确定是否要将其用作复制,但本质上是相同的问题:。基本上,区别在于
knight.moreparrot=x
将新值重新分配给变量,但是knight.egg['Parrot']['More Parrot']=x
修改字典。这是两个完全不同的操作。这会让人更加困惑,但由于某种原因,当我使用垃圾邮件而不是鹦鹉学舌时,这个操作会起作用。