Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

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

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, *pathsegments: str):
        super().__init__(*pathsegments)

Error at instantiation

AttributeError: type object 'Pl' has no attribute '_flavour'

Update: I'm inheriting from WindowsPath still doesn't work.

TypeError: object.__init__() takes exactly one argument (the instance to initialize)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...