2014-06-09 22 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