7

次のコードは私が最初に試したものですが、 を再定義しなかったため、私のバージョンの ではなく、some_path.with_suffix('.jpg')明らかにpathlib.PosixPathオブジェクト (私は Linux を使用しています) を返します。からすべてをコピーする必要がありますか、それともより良い方法がありますか?PosixPathwith_suffixpathlib

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

1 に答える 1

1

Is some_path an instance of your version of Path?

I tested with the following 2 lines appended to your codes:

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

Result is correct: <class '__main__.PosixPath'>

Only when using p = pathlib.Path('test.foo'), result is <class 'pathlib.PosixPath'>

于 2014-12-23T06:53:59.387 に答える