覆盖dict时如何正确覆盖方法keys(),item(),__ iter__?

时间:2018-10-20 05:59:53

标签: python dictionary override

我正在尝试增强dict的功能,以一种在dict中完成的方式来支持特定文件夹中的文件操作。 以下是一个示例

if __name__ == "__main__":
    d = FolderDict("LALALA", create_new=True)
    d["File1"] = "Content of file 1"
    d["File2"] = "Content of file 2"

它将在LALALA文件夹中创建两个具有正确内容的文件。 我可以正确处理get,set,contains,del,pop方法,但似乎无法将手缠在keys(),values(), iter 方法上。

我希望在调用keys()时打印所有文件名,并且在需要时打印

k-文件名 v-文件内容

按照我的代码,请看一下并寻求帮助。

import os


class FolderDict(dict):

    def get_absolute_path(self, file_name):
        return os.path.join(self.folder_path, file_name)

    def __init__(self, folder_path, create_new=False):
        super().__init__()
        self.folder_path = folder_path
        if os.path.exists(self.folder_path) and os.path.isdir(self.folder_path):
            for file_name in os.listdir(self.folder_path):
                with open(self.get_absolute_path(file_name), "r") as reader:
                    self[file_name] = reader.read()
        else:
            if create_new:
                os.makedirs(folder_path, exist_ok=True)
            else:
                raise FileNotFoundError("[Errno 2] No such file or directory: '{}'".format(self.folder_path))

    def __getitem__(self, item):
        with open(self.get_absolute_path(item), "r") as reader:
            return reader.read()

    def __setitem__(self, key, value):
        """
        Be careful,it will overwrite the existing file.
        We support w mode not a mode now
        """
        with open(self.get_absolute_path(key), "w") as writer:
            writer.write(value)

    def keys(self):
        yield from super().keys()

    def __iter__(self):
        yield from self.keys()

    def __contains__(self, item):
        return os.path.exists(self.get_absolute_path(item))

    def __missing__(self, key):
        raise FileNotFoundError("[Errno 2] No such file or directory: '{}'".format(self.get_absolute_path(key)))

    def __delitem__(self, key):
        os.remove(self.get_absolute_path(key))

    def get(self, k, default=None):
        return self[k] if k in self else default

    def pop(self, k):
        content = self[k]
        os.remove(self.get_absolute_path(k))
        return content

    def __repr__(self):
        return "FolderDict for folder {}".format(self.folder_path)

    __str__ = __repr__


if __name__ == "__main__":
    d = FolderDict("LALALA", create_new=True)
    d["File1"] = "Content of file 1"
    d["File2"] = "Content of file 2"
    d["File3"] = "Content of file 3"

    for k,v in d:
        print(k)

1 个答案:

答案 0 :(得分:1)

1:您甚至没有保存文件名的信息,因此您的keys()函数不起作用

2:继承UserDict类,而不是继承dict

3:我看不出dict / UserDict等继承类的含义是什么。

4:要像真实字典一样使用FolderDict,需要在类中写interface xxx { int numbers(); String names(); Double salary(); } abstract class GetNames implements xxx { public String names() { return "Ravi"; } public Double salary() { return null;//just return null; } } class Check extends GetNames { public int numbers() { return 3; } public double sal() { return 25000.00; } } ......。

__iter__  __next__ __getitem__  __setitem__  __next__  __getattribute__   __delitem__ keys items values