Il seguente codice è quello che ho provato prima, ma some_path.with_suffix('.jpg')
ritorna ovviamente un oggetto pathlib.PosixPath
(io sono su Linux) invece che la mia versione di PosixPath
, perché non ha ridefinito with_suffix
. Devo copiare tutto da pathlib
o c'è un modo migliore?Python 3.4+: Estensione pathlib.Path
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__ =()
Forse hanno un decoratore funzione che converte 'pathlib.Path' restituisce la classe' Path', quindi usa '__metaclass__' o decoratori di classi per applicare questo decoratore a tutti i metodi di classe. – kalhartt
Non vedo perché dovresti aver bisogno di farlo. 'with_suffix()' chiama '_from_parsed_parts()', che chiama 'object .__ new __ (cls)'. 'cls' è la tua classe personalizzata, non qualcosa da' pathlib', quindi non vedo come potresti finire con una classe 'pathlib' qui. Qualcuno ha qualche idea? Forse OP ha bisogno di sovrascrivere '__repr __()' per vedere la differenza? – Kevin