我讀了一些關於類和實例變量的信息,並且看到了爲實現工廠模式而進行的各種職位......我說我很漂亮對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
用戶定義的類名應該以大寫字母開頭:'類項目(對象)'。這有助於將它們與實例區分開來(像'str'和'dict'這樣的內置類型已經足夠熟悉而不需要這種視覺線索)。 – chepner