Skip to main content
 首页 » 编程设计

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

2025年05月04日10emanlee

我已经阅读了一些关于类与实例变量的内容,并看到了关于为我正在尝试做的事情实现工厂模式的各种帖子......说我是 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 

请您参考如下方法:

您正确地声明了您的类变量,但是您没有正确地使用它们。不要使用 self 除非您使用实例变量。你需要做的是:

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

通过使用类名而不是自身,您现在正在使用类变量。

因为 _serialnumber 确实用于您不必在 init 函数之外声明的实例。此外,在阅读实例时,您可以只使用 item.item_list。你不必使用 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