使用字典作为lin更改对象

2024-10-05 12:24:19 发布

您现在位置: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,
             '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)

Tags: testself字典deflinkchangeprintdog
3条回答

只需使用内置的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']

你可能想要这个:

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()

不同之处在于在__init__方法中使用字典(link),并将其声明为类属性(变量)。你知道吗

def change(self):
    self.dog = 'bark'
    self.cats.append('meow')

当你这么做的时候

link = {'dog' : self.dog,
         'cats': self.cats}

只有self.dogself.cats的值被存储,而不是实际的实例。你知道吗

相关问题 更多 >

    热门问题