Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.4+;:扩展pathlib.Path_Python_Python 3.x_Path_Pathlib - Fatal编程技术网

Python 3.4+;:扩展pathlib.Path

Python 3.4+;:扩展pathlib.Path,python,python-3.x,path,pathlib,Python,Python 3.x,Path,Pathlib,下面的代码是我首先尝试的,但是一些路径。带有后缀('.jpg')显然返回一个pathlib.PosixPath对象(我在Linux上),而不是我的PosixPath,因为我没有用后缀重新定义。我必须从pathlib复制所有内容吗?还是有更好的方法 import os import pathlib from shutil import rmtree class Path(pathlib.Path): def __new__(cls, *args, **kwargs):

下面的代码是我首先尝试的,但是
一些路径。带有后缀('.jpg')
显然返回一个
pathlib.PosixPath
对象(我在Linux上),而不是我的
PosixPath
,因为我没有用后缀重新定义
。我必须从
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
版本的实例吗

我在代码中附加了以下两行代码进行了测试:

p = Path('test.foo')
print(type(p.with_suffix('.bar')))
结果正确:


只有在使用
p=pathlib.Path('test.foo')
时,结果才是

可能有一个函数修饰符将
pathlib.Path
结果转换为
Path
类,然后使用
元类或类修饰符将此修饰符应用于所有类方法。我不明白为什么需要这样做<带有后缀()的代码>从调用对象的已解析部分()调用
cls
是您的自定义类,而不是
pathlib
中的任何内容,因此我不知道您如何在这里使用
pathlib
类。有人有什么想法吗?也许OP需要重写
\uuuu repr\uuuu()
以查看差异?它应该是我的
路径的一个实例,但我不确定,问题不再发生(在阅读源代码后,我不明白为什么会发生)。这种情况下的标准程序是什么?我是否应该删除这个问题?