这段代码:
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
指向的位置?
编辑:
我不知道是否可以使用字典做我想做的事情,但是 setattr()
和 getattr()
可以很好地工作。
def change(self):
setattr(self, 'dog', 'bark')
cats = getattr(self, 'cats')
cats.append('meow')
setattr(self, 'cats', cats)
最佳答案
您只需使用所有类实例都具有的内置 link
字典即可完成您想要的操作:self.__dict__
。这就是我的意思:
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']
bark ['meow', 'meow']
关于python - 使用字典作为链接更改对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44098132/