Python 3.4+;:扩展pathlib.Path
下面的代码是我首先尝试的,但是Python 3.4+;:扩展pathlib.Path,python,python-3.x,path,pathlib,Python,Python 3.x,Path,Pathlib,下面的代码是我首先尝试的,但是一些路径。带有后缀('.jpg')显然返回一个pathlib.PosixPath对象(我在Linux上),而不是我的PosixPath,因为我没有用后缀重新定义。我必须从pathlib复制所有内容吗?还是有更好的方法 import os import pathlib from shutil import rmtree class Path(pathlib.Path): def __new__(cls, *args, **kwargs):
一些路径。带有后缀('.jpg')
显然返回一个pathlib.PosixPath
对象(我在Linux上),而不是我的PosixPath
,因为我没有用后缀重新定义。我必须从pathlib
复制所有内容吗?还是有更好的方法
import os
import pathlib
from shutil import rmtree
class Path(pathlib.Path):
def __new__(cls, *args, **kwargs):
if cls is Path:
cls = WindowsPath if os.name == 'nt' else PosixPath
self = cls._from_parts(args, init=False)
if not self._flavour.is_supported:
raise NotImplementedError("cannot instantiate %r on your system"
% (cls.__name__,))
self._init()
return self
def with_stem(self, stem):
"""
Return a new path with the stem changed.
The stem is the final path component, minus its last suffix.
"""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [stem + self.suffix])
def rmtree(self, ignore_errors=False, onerror=None):
"""
Delete the entire directory even if it contains directories / files.
"""
rmtree(str(self), ignore_errors, onerror)
class PosixPath(Path, pathlib.PurePosixPath):
__slots__ = ()
class WindowsPath(Path, pathlib.PureWindowsPath):
__slots__ = ()
some_path
是您的path
版本的实例吗
我在代码中附加了以下两行代码进行了测试:
p = Path('test.foo')
print(type(p.with_suffix('.bar')))
结果正确:
只有在使用p=pathlib.Path('test.foo')
时,结果才是
可能有一个函数修饰符将pathlib.Path
结果转换为Path
类,然后使用元类或类修饰符将此修饰符应用于所有类方法。我不明白为什么需要这样做<带有后缀()的代码>从调用对象的已解析部分()调用cls
是您的自定义类,而不是pathlib
中的任何内容,因此我不知道您如何在这里使用pathlib
类。有人有什么想法吗?也许OP需要重写\uuuu repr\uuuu()
以查看差异?它应该是我的路径的一个实例,但我不确定,问题不再发生(在阅读源代码后,我不明白为什么会发生)。这种情况下的标准程序是什么?我是否应该删除这个问题?