Error with simple subclassing of pathlib.Path: no _flavour attribute

前端 未结 3 1376
广开言路
广开言路 2020-12-21 14:46

I\'m trying to sublclass Path from pathlib, but I failed with following error at instantiation

from pathlib import Path
class Pl(Path):
    def __init__(self         


        
3条回答
  •  一整个雨季
    2020-12-21 15:26

    Part of the problem is that the Path class implements some conditional logic in __new__ that doesn't really lend itself to subclassing. Specifically:

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

    This sets the type of the object you get back from Path(...) to either PosixPath or WindowsPath, but only if cls is Path, which will never be true for a subclass of Path.

    That means within the __new__ function, cls won't have the_flavourattribute (which is set explicitly for the*WindowsPath and *PosixPath classes), because your Pl class doesn't have a _flavour attribute.

    I think you would be better off explicitly subclassing one of the other classes, such as PosixPath or WindowsPath.

提交回复
热议问题