python - pathlib.Path 的简单子类化错误:没有 _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'
更新:我继承自WindowsPath
仍然不起作用。
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
解决方案
部分问题是Path
该类实现了一些条件逻辑,__new__
这并不适合子类化。具体来说:
def __new__(cls, *args, **kwargs):
if cls is Path:
cls = WindowsPath if os.name == 'nt' else PosixPath
这会将您返回的对象的类型设置为Path(...)
或PosixPath
,WindowsPath
但仅限if cls is Path
于 ,对于 的子类永远不会如此Path
。
这意味着在__new__
函数中,cls won't have the
_flavour attribute (which is set explicitly for the
*WindowsPath 和*PosixPath
类),因为您的Pl
类没有_flavour
属性。
我认为你最好明确地继承其他类之一,例如PosixPath
or WindowsPath
。
推荐阅读
- javascript - gulpfile 错误接收了一个非乙烯基对象
- tensorflow - 如何在没有源代码的情况下修改预训练的 tensorflow 模型?
- css - 将浮动 div 对齐到中心但最后不是向左整行
- google-dl-platform - 如何创建预装了 tensorflow 或 pytorch 的 GPU VM?
- wordpress - Nginx/.htacces 重定向无法正常工作
- java - 首次安装时出现 LibGdx 错误
- python - 如何访问 tf.data.Dataset.list_files() 收集的文件名?
- r - R中带有面板数据的空间回归
- java - Java可以直接在硬件上运行吗?
- javascript - 使用 javascript 管理对象