【发布时间】:2015-01-12 23:23:11
【问题描述】:
下面的代码是我首先尝试的,但是some_path.with_suffix('.jpg') 显然返回了一个pathlib.PosixPath 对象(我在Linux 上)而不是我的PosixPath 版本,因为我没有重新定义with_suffix。我必须从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__ = ()
【问题讨论】:
-
也许有一个函数装饰器将
pathlib.Path结果转换为Path类,然后使用__metaclass__或类装饰器将此装饰器应用于所有类方法。 -
我不明白您为什么需要这样做。
with_suffix()调用_from_parsed_parts(),后者调用object.__new__(cls)。cls是您的自定义类,而不是pathlib中的任何内容,所以我看不出您如何在这里得到pathlib类。谁有想法?也许 OP 需要覆盖__repr__()才能看到区别?
标签: python python-3.x path pathlib