这段代码:
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']
