使用python类变量来管理全局列表(池)

时间:2013-10-31 17:17:44

标签: python

我已经阅读了类和实例变量的一些内容,并看到了关于实现工厂模式的各种帖子,我正在努力做...我说我对Python很陌生并且希望能够理智是为了安全检查这个问题,一般情况下是好的还是差的设计。

我基本上想拥有一个可以动态实例化的类,让它管理自己的全局列表。因此,如果需要,我可以引用该类的任何实例并访问所有其他实例。在我看来,这样做的好处是允许任何函数访问全局列表(并且类本身为每个实例分配唯一标识符等等。所有封装在类中。)

这是一个我想要采用的简化方法......是正确的形式,和/或我在这种方法中滥用了类变量的概念(在本例中是我的列表)?

感谢您的建议...当然可以随意指出其他帖子来回答这个问题。我继续阅读它们,但我不确定我是否找到了正确的答案。

杰夫

class item(object):

    _serialnumber = -1  # the unique serial number of each item created.

    # I think we refer to this (below) as a class variable in Python? or is it really?  
    # This appears to be the same "item_list" across all instances of "item", 
    # which is useful for global operations, it seems

    item_list = []    

    def __init__(self, my_sn):
        self.item_list.append(self)
        self._serialnumber = my_sn

# Now create a bunch of instances and initialize serial# with i.
# In this case I am passing in i, but my plan would be to have the class automatically
# assign unique serial numbers for each item instantiated.

for i in xrange(100,200):
    very_last_item = item(i)  

# Now i can access the global list from any instance of an item

for i in very_last_item.item_list:
    print "very_last_item i sn = %d" % i._serialnumber

1 个答案:

答案 0 :(得分:1)

您正确声明了类变量,但未正确使用它们。除非您使用实例变量,否则请勿使用self。你需要做的是:

item.item_list.append(self)
item._serialnumber = my_sn

通过使用类名而不是self,您现在使用的是类变量。

_serialnumber is really used for the instance you dont have to declare outside the init function. Also when reading the instances you can just use item.item_list . you dont have to use the very_last_item`

class item(object):



    # I think we refer to this (below) as a class variable in Python? or is it really?  
    # This appears to be the same "item_list" across all instances of "item", 
    # which is useful for global operations, it seems

    item_list = []    

    def __init__(self, my_sn):
        item.item_list.append(self)
        self._serialnumber = my_sn

# Now create a bunch of instances and initialize serial# with i.
# In this case I am passing in i, but my plan would be to have the class automatically
# assign unique serial numbers for each item instantiated.

for i in xrange(1,10):
    very_last_item = item(i)  

# Now i can access the global list from any instance of an item


for i in item.item_list:
    print "very_last_item i sn = %d" % i._serialnumber