自定义pathlib.Path()

自定义pathlib.Path(),path,python-3.7,pathlib,Path,Python 3.7,Pathlib,我尝试使用额外的功能自定义pathlib.Path()。特别是,我非常喜欢使用上下文管理器作为进出目录的方法。我一直在使用它,但在让Path()与自定义上下文管理器一起工作时,似乎出现了错误。有人知道为什么下面的代码会导致错误吗?我如何修复它,而不必在自定义类中重新创建所有Path() # Python 3.7.3; Ubuntu 18.04.1 from pathlib import Path import os class mypath(Path): def __enter__(se

我尝试使用额外的功能自定义pathlib.Path()。特别是,我非常喜欢使用上下文管理器作为进出目录的方法。我一直在使用它,但在让Path()与自定义上下文管理器一起工作时,似乎出现了错误。有人知道为什么下面的代码会导致错误吗?我如何修复它,而不必在自定义类中重新创建所有Path()

# Python 3.7.3; Ubuntu 18.04.1
from pathlib import Path
import os
class mypath(Path):
    def __enter__(self):
        self.prdir = os.getcwd()
        os.chdir(str(self))
    def __exit__(self,**error_stuff):
        os.chdir(self.prdir)

p = mypath('~').expanduser()
...
AttributeError: type object 'mypath' has no attribute '_flavour'

如果您从派生的具体类(而不是路径)生成子类,那么它是有效的

from pathlib import PosixPath
import os
class mypath(PosixPath):
    def __enter__(self):
        print('Entering...')
        self.prdir = os.getcwd()
        os.chdir(str(self))
    def __exit__(self, e_type, e_value, e_traceback):
        os.chdir(self.prdir)
        print('Exiting...')

p = mypath('~').home()
with p:
    # print(p.prdir)
    print(p)
不幸的是,我不知道为什么会这样。你可能想更一般一些。经过一些研究,我发现这个问题比看起来要好得多。这似乎与
Path
的创建方式有关(它选择
PosixPath
WindowsPath
的方式),因为
Path
的子类无法复制该行为

见凯文的答案

请看一下讨论和解释


我现在看不清楚。您还可以尝试查看pathlib源代码。

刚刚用一个非常简洁的解释链接(Kevin的链接)更新了我的答案。天哪,您真是个天才。真不敢相信我没有想到要从这个类的父类扩展。