python - 如何使用一种方法通过某个值更新一个对象的不同集合?

标签 python python-3.x algorithm

我有两个相同的方法来更新某个值的列表:

 def block_device(self, device_id):
    if self.block_device_ids is None:
        self.block_device_ids = []
    if device_id not in self.block_device_ids:
        self.block_device_ids.append(device_id)
        self.save()
        return True
    return False

 def add_video(self, video_id):
    if self.video_ids is None:
        self.video_ids = []
    if video_id not in self.video_ids:
        self.video_ids.append(video_id)
        self.save()
        return True
    return False

如何创建一种方法 update_collection 并在两种情况下都使用它?

我创建了以下解决方案:

async def update_collection(self, collection, item, attr_name):
    if collection is None:
        collection = []
    if item not in collection:
        getattr(self, attr_name).append(item)
        await self.save()
        return True
    return False

 async def add_video(self, video_id):
    return await self.update_collection(self.video_ids, video_id, 'video_ids')

 async def block_device(self, device_id):
    return await self.update_collection(self.block_device_ids, device_id, 'device_ids')

但由于 collection = [] 而无法正常工作。如何解决这个问题? 有什么我可以改进的吗?

最佳答案

您不需要传入集合属性的名称:

async def update_collection(self, item, attr_name):
    collection = getattr(self, attr_name)
    if collection is None:
        setattr(self, attr_name, [])
        collection = getattr(self, attr_name)
    if item not in collection:
        collection.append(item)
        await self.save()
        return True
    return False

注意:您的代码的最后一行有一个错误:传入的 attr_name 应该是“block_device_ids”而不是“device_ids”

关于python - 如何使用一种方法通过某个值更新一个对象的不同集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285434/

相关文章:

python - Discord.py 记录删除和编辑的消息

python - 将 csv 写入谷歌云存储

python - 如何调用 json 字典中列表中的值

algorithm - 获取数组中索引相反的元素的最佳方法是什么?

python - 如何查找用户是否输入了主机名或 IP 地址?

python - MySQL 查询 : check the syntax near '?' . 中的语法错误 '?' 来自哪里?

python - 在 Python 3 中将字节转换为十六进制字符串的正确方法是什么?

python - 内置容器的迭代器

algorithm - 如何用DP解决 "Longest similar subsequence"

algorithm - 为什么我们对排序一个已经排序的文件需要多长时间感兴趣?