我正在尝试从pathlib继承Path,但是在实例化时出现以下错误而失败
from pathlib import Path
class Pl(Path):
def __init__(self, *pathsegments: str):
super().__init__(*pathsegments)
实例化时出错
AttributeError: type object 'Pl' has no attribute '_flavour'
我正在尝试从pathlib继承Path,但是在实例化时出现以下错误而失败
from pathlib import Path
class Pl(Path):
def __init__(self, *pathsegments: str):
super().__init__(*pathsegments)
实例化时出错
AttributeError: type object 'Pl' has no attribute '_flavour'
Part of the problem is that the
Path
class implements some conditional logic in__new__
that doesn't really lend itself to subclassing. Specifically:This sets the type of the object you get back from
Path(...)
to eitherPosixPath
orWindowsPath
, but onlyif cls is Path
, which will never be true for a subclass ofPath
.That means within the
__new__
function,cls won't have the
_flavourattribute (which is set explicitly for the
*WindowsPath and*PosixPath
classes), because yourPl
class doesn't have a_flavour
attribute.I think you would be better off explicitly subclassing one of the other classes, such as
PosixPath
orWindowsPath
.Path
is somewhat of an abstract class that is actually instantiated as on of two possible subclasses depending on the OS:PosixPath
orWindowsPath
https://docs.python.org/3/library/pathlib.html
This base class looks for an internal (private) class variable to determine what type of object it actually is, and this variable is called
_flavour
您有两种选择:
该代码将如下所示:
This is not recommended as you will be using undocumented elements that could break at any time with any change to the library, but it will allow you to inherit from
Path
directly.请注意,如果您决定使用此方法,可能还会有其他问题!