2014-06-07 24 views
-1

我有一個類,我想擁有所有的功能,但我不希望他是可配置的(通過初始化,冷凍設置可迭代)。重新加載子集的冷凍集

此外,我希望他有'重新加載'的功能 - 我從服務器加載靜態列表,所以用戶不能改變它(所以我不希望用戶認爲他可以改變它)。 服務器上的列表可以由管理員更改,所以我需要重新加載選項。

這就是我希望的:

class A(frozenset): 
    def __init__(self, list_id): 
     super().__init__() 
     self.list_id = list_id 
     self.reload() 

    def reload(self): 
     #loading staff by self.list_id... 
     pass 

但我沒有找到一個方法來「添加」新員工類(我試圖重新初始化它)。

可能是我使用了錯誤的工作人員,所以如果你有這一點,細花葯方式(我需要之間的差異比較對象的差異選擇):

a = A(1) 
b = A(2) 
len(a) 
iter(a) 
a.difference(b) 

可能是超載添加和更新設置會很好,但我不想這樣做(它在代碼中看起來很糟糕,因爲有更多類似於更新的函數)。

回答

1

您無法更新frozenset內容,否;它仍然是不可變的,即使是分類。

您可以改爲collections.abc.Set() Abstract Base Class的子類;它也建模一個不可變的集合;所有你需要做的是真正實現在Abstract Methods column列出的方法,其餘的是照顧你:

from collections.abc import Set 

class A(Set): 
    def __init__(self, list_id): 
     self.list_id = list_id 
     self.reload() 

    def reload(self): 
     values = get_values(self.list_id) 
     self._values = frozenset(values) 

    def __contains__(self, item): 
     return item in self._values 

    def __iter__(self): 
     return iter(self._values) 

    def __len__(self): 
     return len(self._values) 

built-in frozenset type的所有方法來實現;您可以輕鬆地提供缺少的,因爲這些是操作員方法的別名:

def issubset(self, other): 
    return self <= frozenset(other) 

def issuperset(self, other): 
    return self >= frozenset(other) 

def union(self, *others): 
    res = self 
    for o in others: 
     res |= frozenset(o) 
    return res 

def intersection(self, *others): 
    res = self 
    for o in others: 
     res &= frozenset(o) 
    return res 

def difference(self, *others): 
    res = self 
    for o in others: 
     res -= frozenset(o) 
    return res 

def symmetric_difference(self, other): 
    return self^frozenset(other)