首页 > 解决方案 > 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)

标签: python

解决方案


部分问题是Path该类实现了一些条件逻辑,__new__这并不适合子类化。具体来说:

    def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath

这会将您返回的对象的类型设置为Path(...)PosixPathWindowsPath但仅限if cls is Path于 ,对于 的子类永远不会如此Path

这意味着在__new__函数中,cls won't have the_flavour attribute (which is set explicitly for the*WindowsPath 和*PosixPath类),因为您的Pl类没有_flavour属性。

我认为你最好明确地继承其他类之一,例如PosixPathor WindowsPath


推荐阅读