簡體   English   中英

Python 3.4+:擴展pathlib.Path

[英]Python 3.4+: Extending pathlib.Path

下面的代碼是我首先嘗試的,但是some_path.with_suffix('.jpg')顯然會返回一個pathlib.PosixPath對象(我在Linux上)而不是我的PosixPath版本,因為我沒有重新定義with_suffix 我是否必須從pathlib復制所有內容,還是有更好的方法?

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__ = ()

some_path是您的Path版本的實例嗎?

我測試了你的代碼附加了以下2行:

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

結果是正確的: <class '__main__.PosixPath'>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM