2014-06-09 27 views
1

我嘗試使文件夾中的文件名包含類。但我希望它像集合一樣行事。現在我有這樣的:使自定義類的行爲像集

class Files(): 

    def __init__(self, in_dir): 
     self.in_dir = in_dir 
     self.files = set(map(os.path.basename, glob.glob(self.in_dir + "/*.txt"))) 

    def __add__(self, other): 
     return self.files + other.files  

    def __or__(self, other): 
     return self.files | other.files 

    def __and__(self, other): 
     return self.files & other.files 

    def __xor__(self, other): 
     return self.files^other.files 

這項工作,我可以這樣做:

f1 = Files(inDir1) 
f2 = Files(inDir2) 

diff_files = f1^f2 % this give files that are in f1 or f2 folder but not in both folders 

這是好的,但問題是,diff_files不是Files實例。如何改變我的類,像在python 3.x中設置一樣?

+0

任何你不使用'set'可怕原因ctly?我想有更多的代碼沒有被顯示,但是現在我會把'__init__'中的代碼作爲一個函數返回一個集合。 –

+0

這是一個小例子。我希望文件具有自定義功能,如刪除self.files中的文件。 – user3654650

回答

3

首先,in_dir參數可選:

此外

def __xor__(self, other): 
    instance = Files() 
    instance.files = self.files^other.files 
    return instance 

,我沒有看到保持in_dir作爲一個實例變量的原因:

def __init__(self, in_dir=None): 
    if in_dir: 
     self.in_dir = in_dir 
     self.files = set(map(os.path.basename, glob.glob(self.in_dir + "/*.txt"))) 

然後,更改__xor__()。您可以簡化__init__()

def __init__(self, in_dir=None): 
    if in_dir: 
     self.files = set(map(os.path.basename, glob.glob(in_dir + "/*.txt"))) 

或者,您也可以允許通過傳遞files集合初始化Files

def __init__(self, in_dir=None, files=None): 
    if in_dir: 
     self.files = set(map(os.path.basename, glob.glob(in_dir + "/*.txt"))) 
    if files: 
     self.files = files 

然後,__xor__()方法會更簡單:

def __xor__(self, other): 
    return Files(files=self.files^other.files) 
+0

謝謝。我也考慮擴展集合類,但不知道如何。這比現在好嗎? – user3654650

+0

@ user3654650我對你現在使用的方法非常滿意。但是,無論如何看看:http://stackoverflow.com/questions/798442/what-is-the-correct-or-best-way-to-subclass-the-python-set-class-adding-a-new和http://www.itmaybeahack.com/book/python-2.6/html/p03/p03c04_extending.html。希望有所幫助。 – alecxe

1

我不知道我明白你的意思是「行爲像set」,但我不明白,你想返回的Files一個實例,而不是隻有「差異」,所以認爲:

變化:

def __xor__(self, other): 
     return self.files^other.files 

到:

def __xor__(self, other): 
     result = Files() 
     result.in_dir = self.in_dir 
     result.files = self.files^other.files 
     return result