gpt4 book ai didi

python - 使自定义类表现得像集合

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:45 25 4
gpt4 key购买 nike

我尝试创建一个包含文件夹中文件名的类。但我希望它表现得像集合。现在我有这个:

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 中的设置?

最佳答案

首先,使 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__():

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

此外,我看不出将 in_dir 保留为实例变量的原因。您可以简化 __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)

关于python - 使自定义类表现得像集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com