Python在模块中存储预定义列表并以简单的方式编辑它们

2024-05-16 23:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我不确定这是否最好通过上课来完成,或者是否有更整洁的方法来完成

我正在编写一个模块,在其中我希望某些列表是预定义的,易于访问,但也可以更改。将会有很多这样的列表,可能有20-30个

这些列表的示例如下:

fruits = ['apple','pear','peach']
nuts = ['peanuts','cashew','almonds']

我还想拥有两个功能,允许用户在此列表中添加或删除项目:

my_mod.add(nuts, ['macademia','brazil'])
my_mod.remove(fruits, ['apple'])

所以我想写一节课:

class Food:
    def __init__ (self):
        self.fruits = ['apple','pear','peach']
        self.nuts = ['peanuts','cashew','almonds']

    def add(self, add_items):
        self.<????> += add_items

但是你可以看到我的问号在哪里,如果我这样做,我不知道如何将它添加到用户提供的列表名中

我这样做是正确的还是有更好的方法来实现我的愿望

我的另一个想法是使用dict并在模块的__init__文件中定义它

但我对这个想法不太感兴趣,因为我认为它可能会令人困惑


Tags: 模块方法用户selfaddapple列表my
2条回答

我的建议是使用.xml.json来定义此列表的内容,就像一种配置。这样,您就可以在python代码中,简单地读取root级别tree并以编程方式向下钻取,而无需硬编码任何内容,同时为最终用户提供添加/删除的灵活性。这也意味着最终用户更改此config文件时不需要修改任何python objects

让我举例说明。我们有一个用户定义列表的配置,比如udl_config.xml,它看起来像:

<main>
    <fruits>
        <elem>apple</elem>
    .....
    </fruits>
    <nuts>
         .....
    </nuts>
    .....
</main>

然后在python代码中,您将拥有:

import xml.etree.ElementTree as ET
main_tree = ET.parse('udl_config.xml')
main_root = main_tree.getroot()

使用xml parse library的find()text()函数动态地向下搜索并对它们执行必要的操作

有几种方法可以做到这一点:

1-带列表和“eval”功能:此功能有效;但这是不明智的,因为如果您不知道自己在做什么,使用“eval”用户可能会注入恶意代码。

class User:
    fruits = ['apple','pear','peach']
    nuts = ['peanuts','cashew','almonds']

    def add(self, _list, new_items=[]):
        l = eval('self.%s' % _list)
        l += new_items

    def remove(self, _list, item):
        l = eval('self.%s' % _list)
        l.remove(item)

if __name__ == '__main__':

    user1 = User()
    user1.add('fruits', ['orange', 'lemon'])
    print user1.fruits

    user1.remove('nuts', 'cashew')
    print user1.nuts

2-使用python字典。

class User:
    products = {
                    'fruits': ['apple','pear','peach'],
                    'nuts': ['peanuts','cashew','almonds'],
                }

    def add(self, _list, new_items=[]):
        try:
            self.products[_list] += new_items
        except KeyError:
            print 'The product list entered does not exist'

    def remove(self, _list, item):
        try:
            self.products[_list].remove(item)
        except KeyError:
            print 'The product list entered does not exist'

if __name__ == '__main__':

    user1 = User()
    user1.add('fruits', ['orange', 'lemon'])
    print user1.products['fruits']

    user1.remove('nuts', 'cashew')
    print user1.products['nuts']

    # When the user enters a nonexisting list
    user1.add('vegetables', ['onion'])

3-或使用列表函数的自定义类的最短路径

class Mylist(list):
    def add(self, item):
        self.append(item)

class User:
    fruits = Mylist(['apple','pear','peach'])
    nuts = Mylist(['peanuts','cashew','almonds'])


if __name__ == '__main__':

    user1 = User()


    # TO ADD AN ITEM

    user1.fruits.add('orange')
    print user1.fruits


    # TO REMOVE AN ITEM, (list name must match name of list attribute inside)
    
    user1.nuts.remove('cashew')
    print user1.nuts

相关问题 更多 >