3

I have a situation where I am going to have a lot of lists and the values in each of those lists need to be in some set of valid values. However the set of valid values is going to be different for each list. So before doing any appending to these lists I have to check for membership and that is making for a lot of repeated code. I'm finding myself tempted to extend the list object so that I wont have to do that membership check over and over.

class Attribute(list):
    def __init__(self,validList):
        self.valid = validList

    def append(self,inString):
        if inString not in self.valid:
            raise Exception, '%s is not a valid value for this attribute' % inString
        if inString not in self:
            super(Attribute,self).append(inString)

That way I could have each of my lists with a different valid set of values. However, I feel like extending the built-in objects is not often a good idea and I have avoided it in the past. So my questions are

  1. Is there a built-in way to do this or is there a library that has something like this already?
  2. Is this a bad idea? What issues might arise from doing something like this?

Overriding append method after inheriting from a Python List was helpful in making this code work.

4

1 回答 1

2

我想你可以选择任何一种方式,但通常我会避免子类化列表。例如,我可能会创建自己的集合对象而不是子类化。

在您的情况下,我只会过滤每个列表以检查成员资格。除非您正在处理巨大的记录集,否则这可能不是问题。

list.append(1)
list.append(2)
list.append(3)
# list = [1, 2, 3]

valid_values = (2, 3)

list = [item for item in list if item in valid_values]
# list = [2, 3] now

至于你关于为什么 append 不起作用的问题,这是因为你试图附加一个列表,而不是一个列表项。您可以通过制作它来解决此问题list.append(inString)。如果在某些时候您想将列表实际组合在一起,您可以使用list.extend(other_list)or list + other_list

附带说明一下,Python 中的大多数人都遵循 PEP-8 语法以提高可读性。这意味着inString将被命名为in_string.

于 2013-07-03T16:38:09.950 回答