2013-10-31 74 views
2

我讀了一些關於類和實例變量的信息,並且看到了爲實現工廠模式而進行的各種職位......我說我很漂亮對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 
+0

用戶定義的類名應該以大寫字母開頭:'類項目(對象)'。這有助於將它們與實例區分開來(像'str'和'dict'這樣的內置類型已經足夠熟悉而不需要這種視覺線索)。 – chepner

回答

1

您正確地聲明你的類變量,但你不使用它們正確。除非使用實例變量,否則不要使用self。你需要做的是:

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

使用類名稱,而不是自您現在使用類變量。

因爲_serialnumber is really used for the instance you dont have to declare outside the初始化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 
+0

謝謝 - 這是有幫助的。是的,我試圖將新創建的實例(self)追加到類變量中。出於某種原因,使用「self」作爲參考似乎給了我想要的行爲,但也許有許多副本的列表,而不是所有實例中的單個共享列表。我會給它一個旋轉。再次感謝。 – Jeff

+0

'self'用於訪問,因爲對象本身沒有同名的屬性。明確地使用類名來訪問類的屬性,而不是依賴Python的查找行爲。 – chepner