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,
             '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/

相关文章:

用于静态类型类属性的 Python 模块

python - 检测类是声明式还是函数式定义的——可能吗?

python - 根据其他列修改数据框列中的值

Python - 从子目录中找不到的目录文件中读取文件(在那里)

python - 为什么 pathlib.Path ("C:") 解析为 Windows 上的工作目录?

Python 在(子)函数内传递变量

Python 3D 绘制测量数据

python - 使用pip时“SSLError: The read operation timed out”

python按值排序json列表

python - 使用 Python 的 xlsxwriter 在 Excel 中的字符串条件格式 "equal to"