2014-11-15 23 views
7

Mã sau đây là những gì tôi đã thử trước, nhưng some_path.with_suffix('.jpg') rõ ràng trả về đối tượng pathlib.PosixPath (Tôi đang sử dụng Linux) thay vì phiên bản PosixPath vì tôi không xác định lại with_suffix. Tôi có phải sao chép mọi thứ từ pathlib hoặc có cách nào tốt hơn không?Python 3.4+: Mở rộng 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

Có lẽ có một chức năng trang trí rằng cải đạo 'pathlib.Path' dẫn đến lớp' Path' của bạn, sau đó sử dụng '__metaclass__' hoặc trang trí lớp để áp dụng trang trí này cho tất cả các phương thức lớp. – kalhartt

+1

Tôi không hiểu tại sao bạn nên làm điều đó. 'with_suffix()' gọi '_from_parsed_parts()', gọi 'đối tượng .__ new __ (cls)'. 'cls' là lớp tùy chỉnh của bạn, không phải bất cứ thứ gì từ' pathlib', vì vậy tôi không thấy cách bạn có thể kết thúc với một lớp 'pathlib' ở đây. Ai có ý tưởng gì không? Có lẽ OP cần ghi đè '__repr __()' để thấy sự khác biệt? – Kevin

Trả lời

1

some_path một thể hiện của các phiên bản của Path?

Tôi đã thử nghiệm với 2 dòng sau nối vào mã của bạn:

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

Kết quả là chính xác: <class '__main__.PosixPath'>

Chỉ khi sử dụng p = pathlib.Path('test.foo'), kết quả là <class 'pathlib.PosixPath'>

+0

Nó phải là một thể hiện của 'Path' của tôi, nhưng tôi không biết chắc chắn và vấn đề không xảy ra nữa (và sau khi đọc mã nguồn, tôi không thấy lý do tại sao nó nên). Thủ tục tiêu chuẩn cho các tình huống như thế này là gì? Tôi có nên xóa câu hỏi đơn giản không? – Joschua