Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 自定义定义类上的循环_Python_Python 3.x_Oop_Iterator - Fatal编程技术网

Python 自定义定义类上的循环

Python 自定义定义类上的循环,python,python-3.x,oop,iterator,Python,Python 3.x,Oop,Iterator,我制作了一个类文件来保存文件的一些属性: class file: def __init__(self, filepath): self.path = filepath self.name = self.getName() self.type = self.getType() def getName(self): return Path(self.path).stem def getType(self):

我制作了一个类
文件
来保存文件的一些属性:

class file:
    def __init__(self, filepath):
        self.path = filepath
        self.name = self.getName()
        self.type = self.getType()

    def getName(self):
        return Path(self.path).stem

    def getType(self):
        return 'some filetype'

    def getContent(self):
        with open(self.path, 'rt') as fid:
            return fid.read()
现在我想存储许多文件的属性,并轻松获得所有文件的特定属性,因此我制作了一个
files
类:

class files:
    def __init__(self):
        self.list = []

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

    def add(self, file):
        self.list.append(file)

    def getNames(self):
        return [file.name for file in self.list]

    def getTypes(self):
        return [file.type for file in self.list]

    def getPaths(self):
        return [file.path for file in self.list]
这允许我通过执行以下操作获取所有文件名

somefiles = files()
somefiles.add(file('src/test.txt')) # and some other

filenames = somefiles.getNames()
通过实现
\uuuu iter\uuuu
方法,这也允许我通过执行以下操作循环
文件中的列表:

for file in somefiles:
    pass

这是在类的“子对象”上循环的Python方式吗?将我的
文件
实例存储在列表中,然后通过执行
iter(self.list)
将其转换为iterable,这似乎有点奇怪。什么是蟒蛇式的方式

yield from self.list
?在问自己是否有一种更符合pythonic的方法来做X之前,首先问问自己X的哪些地方不符合pythonic。即使是[1,2,3]中x的
:…
也能工作,因为
iter([1,2,3])
返回类型为
list\u迭代器的对象,而不是列表本身。@DanielMesejo这才有效@切普纳,也就是说,这无关紧要?是的,这是一种非常正常的方式。当列表迭代器对象已经存在时,不要创建一个无意义的生成器。
从self.list中屈服。
?在问自己是否有一种更符合pythonic的方法来做X之前,首先问问自己X有什么不符合pythonic的地方。即使是[1,2,3]中x的
:…
也能工作,因为
iter([1,2,3])
返回类型为
list\u迭代器的对象,而不是列表本身。@DanielMesejo这才有效@切普纳,也就是说,这无关紧要?是的,这是一种非常正常的方式。当列表迭代器对象已经存在时,不要创建无意义的生成器。