2014-11-15 3 views
7

다음 코드는 내가 먼저 시도 것입니다,하지만 난 with_suffix를 다시 정의하지 않았기 때문에 some_path.with_suffix('.jpg') 분명히하는 pathlib.PosixPath 객체 (I 리눅스에있어) 대신 PosixPath의 내 버전을 반환합니다. pathlib에서 모든 것을 복사해야합니까, 아니면 더 좋은 방법이 있습니까? some_pathPath 버전의 인스턴스파이썬 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__ =() 
+0

은 어쩌면 변환 함수 장식이있다 'pathlib.Path' 결과가'Path' 클래스에 전달 된 다음'__metaclass__' 또는 클래스 데코레이터를 사용하여이 데코레이터를 모든 클래스 메소드에 적용합니다. – kalhartt

+1

왜 그렇게해야하는지 모르겠습니다. 'with_suffix()'는'object .__ new __ (cls)'를 호출하는'_from_parsed_parts()'를 호출합니다. 'cls'는 당신의 커스텀 클래스이고,'pathlib'에서 나온 것이 아닙니다. 그래서 당신이'pathlib' 클래스로 어떻게 끝낼 수 있는지 보지 못했습니다. 누구든지 아이디어가 있습니까? 아마도 차이점을보기 위해 OP는'__repr __()'을 오버라이드해야합니까? – Kevin

답변

1

인가?

p = Path('test.foo') 
print(type(p.with_suffix('.bar'))) 

결과가 정확 :

난 당신의 코드에 추가 된 다음 두 라인에서 테스트 p = pathlib.Path('test.foo')를 사용하는 경우에만 <class '__main__.PosixPath'>

, 결과는 <class 'pathlib.PosixPath'>

+0

내 Path의 인스턴스가되어야하지만 확실하지 않으며 문제가 더 이상 발생하지 않습니다. (그리고 소스 코드를 읽은 후에 왜 그렇게해야하는지 알 수 없습니다.) 이런 상황에 대한 표준 절차는 무엇입니까? 질문을 삭제해야합니까? – Joschua