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

标签 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

最佳答案

您正确地声明了您的类变量,但是您没有正确地使用它们。不要使用 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

关于python - 使用 python 类变量来管理全局列表(池),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19712840/

相关文章:

python - 在这种情况下如何使用 Assert?

python - 如何忽略 numpy 数组中的 NaN 数据点并在 Python 中生成规范化数据?

python - 在(OS X 10.8.4 和 Python 2.7.5)上安装 matplotlib 失败(尝试了所有方法)

Python UnicodeDecodeError : 'utf8' codec can't decode byte. ..意外的代码字节

python - BeautifulSoup 获取字符串之间的链接

python - 如何将脚本参数传递给 pdb (Python)?

python - Jupyter笔记本: Timeout waiting for kernel_info_reply

python - 如何使用python从mongodb获取游标的长度?

python - django-rest-framework:全局限制对 GET 的请求?

python - 有没有办法在 Python 中编辑包含图像的 xlsx 工作簿?