다음 코드는 내가 먼저 시도 것입니다,하지만 난 with_suffix
를 다시 정의하지 않았기 때문에 some_path.with_suffix('.jpg')
분명히하는 pathlib.PosixPath
객체 (I 리눅스에있어) 대신 PosixPath
의 내 버전을 반환합니다. pathlib
에서 모든 것을 복사해야합니까, 아니면 더 좋은 방법이 있습니까? some_path
는 Path
버전의 인스턴스파이썬 3.4 이상 : 확장 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__ =()
은 어쩌면 변환 함수 장식이있다 'pathlib.Path' 결과가'Path' 클래스에 전달 된 다음'__metaclass__' 또는 클래스 데코레이터를 사용하여이 데코레이터를 모든 클래스 메소드에 적용합니다. – kalhartt
왜 그렇게해야하는지 모르겠습니다. 'with_suffix()'는'object .__ new __ (cls)'를 호출하는'_from_parsed_parts()'를 호출합니다. 'cls'는 당신의 커스텀 클래스이고,'pathlib'에서 나온 것이 아닙니다. 그래서 당신이'pathlib' 클래스로 어떻게 끝낼 수 있는지 보지 못했습니다. 누구든지 아이디어가 있습니까? 아마도 차이점을보기 위해 OP는'__repr __()'을 오버라이드해야합니까? – Kevin