自定义路径库.路径()



我尝试自定义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'

如果您从派生的具体类而不是Path派生子类,它就会起作用。

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的方式有关(它选择PosixPathWindowsPath的方式(,因为Path的子类无法复制行为。

点击此处查看Kevin的答案

也请看一下这里的讨论和解释。

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

最新更新