Python 使用字典作为链接更改对象
此代码:Python 使用字典作为链接更改对象,python,Python,此代码: class test(): def __init__(self): self.dog = 'woof' self.cats = ['meow'] print(self.dog, self.cats) self.change() print(self.dog, self.cats) def change(self): link = {'dog' : self.dog,
class test():
def __init__(self):
self.dog = 'woof'
self.cats = ['meow']
print(self.dog, self.cats)
self.change()
print(self.dog, self.cats)
def change(self):
link = {'dog' : self.dog,
'cats': self.cats}
link['dog'] = 'bark'
link['cats'].append('meow')
a = test()
给我这个输出:
woof ['meow']
woof ['meow', 'meow']
当我预料到:
woof ['meow']
bark ['meow', 'meow']
我看到link['dog']='bark'
只是改变了字典,而不是self.dog
本身。如何使用字典更改self.dog的位置
编辑:
我不知道使用dictionary是否可以做我想做的事情,但是setattr()
和getattr()
可以很好地工作
def change(self):
setattr(self, 'dog', 'bark')
cats = getattr(self, 'cats')
cats.append('meow')
setattr(self, 'cats', cats)
当你这么做的时候
link = {'dog' : self.dog,
'cats': self.cats}
只有
self.dog
和self.cats
的值被存储,而不是实际的实例。您可能想要这样:
class Test():
def __init__(self):
self.link = {}
self.link['dog'] = 'woof'
self.link['cats'] = ['meow']
print(self.link['dog'], self.link['cats'])
self.change()
print(self.link['dog'], self.link['cats'])
def change(self):
self.link['dog'] = 'bark'
self.link['cats'].append('meow')
a = Test()
区别在于在
\uuuu init\uuuu
方法中也使用字典(链接
),并将其声明为类属性(变量)。只需使用内置的链接
-类似字典,所有类实例都有:self.\uuu dict\uuu
。我的意思是:
class Test():
def __init__(self):
self.dog = 'woof'
self.cats = ['meow']
print(self.dog, self.cats)
self.change()
print(self.dog, self.cats)
def change(self):
self.__dict__['dog'] = 'bark'
self.__dict__['cats'].append('meow')
a = Test()
输出:
woof['meow']
吠叫
self.dog='bark'
?我建议阅读,你应该用大写字母命名你的类。这就是为什么通过编码:{'dog':self.dog,}
你在字典中用self.dog的值创建键,而不是项本身。@StavrosAvramidis,但是self.cats
对象已更改@alexpad:区别在于,self.dog
的值在一个不可变的对象中是一个字符串,因此有效地复制了它。另一方面,self.cats
是一个可变对象,list
,因此对它的引用存储在字典中…通过它的更改也会影响对类实例中存储的相同list
的引用。谢谢,但我不能直接将self.dog
分配给任何对象。不过,我发现setattr()
会起作用。不,我想间接地改变self.dog
和self.cats
。现在我看到字典中的方法并不总是有效的,但是setattr()
/getattr()
确实有效。谢谢你的回答。如果你找到了解决办法,你可以回答你自己的问题对不起,我不明白你想要什么,你说的“间接”是什么意思。谢谢!虽然我不能完全确定访问\uuu name\uuuu
方法是否被认为是正确的,但这是完全正确的,尤其是在类方法中完成时。
class Test():
def __init__(self):
self.dog = 'woof'
self.cats = ['meow']
print(self.dog, self.cats)
self.change()
print(self.dog, self.cats)
def change(self):
self.__dict__['dog'] = 'bark'
self.__dict__['cats'].append('meow')
a = Test()