2014-11-15 49 views
7

以下代碼是我首先嚐試的,但some_path.with_suffix('.jpg')明顯返回pathlib.PosixPath對象(我在Linux上)而不是我的PosixPath版本,因爲我沒有重新定義with_suffix。我是否需要複製pathlib中的所有內容,或者有更好的方法嗎?Python 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()'調用'_from_parsed_pa​​rts()',調用'object .__ new __(cls)'。 'cls'是你的自定義類,而不是'pathlib'中的任何東西,所以我沒有看到你在這裏最終得到了一個'pathlib'類。有人有主意嗎?也許OP需要重寫'__repr __()'來看看區別? – Kevin

回答

1

some_path您的Path版本的實例?

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

結果是正確的:

我有以下兩行添加到您的代碼測試<class '__main__.PosixPath'>

使用p = pathlib.Path('test.foo')只有當,結果是<class 'pathlib.PosixPath'>

+0

它應該是我的'Path'的一個實例,但我不確定,並且問題不再發生(並且在閱讀源代碼後,我不明白爲什麼它應該)。這種情況的標準程序是什麼?我應該簡單地刪除這個問題嗎? – Joschua