此代码:
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__
,您就可以做您想做的事情。我的意思是:输出:
你可能想要这个:
不同之处在于在
__init__
方法中使用字典(link
),并将其声明为类属性(变量)。你知道吗当你这么做的时候
只有
self.dog
和self.cats
的值被存储,而不是实际的实例。你知道吗相关问题 更多 >
编程相关推荐