2

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

1 回答 1

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初始化function. Also when reading the instances you can just useitem.item_list . you dont have to use thevery_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
于 2013-10-31T17:26:08.630 回答