2014-11-15 47 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