Subclass `pathlib.Path` fails

后端 未结 7 1647
情歌与酒
情歌与酒 2020-12-16 10:24

I would like to enhance the class pathlib.Path but the simple example above dose not work.

from pathlib import Path

class PPath(Path):
    def          


        
7条回答
  •  渐次进展
    2020-12-16 10:35

    You may be able to simplify your life depending on why you want to extend Path (or PosixPath, or WindowsPath). In my case, I wanted to implement a File class that had all the methods of Path, and a few others. However, I didn't actually care if isinstance(File(), Path).

    Delegation works beautifully:

    class File:
    
        def __init__(self, path):
            self.path = pathlib.Path(path)
            ...
    
        def __getattr__(self, attr):
            return getattr(self.path, attr)
    
        def foobar(self):
            ...
    

    Now, if file = File('/a/b/c'), I can use the entire Path interface on file, and also do file.foobar().

提交回复
热议问题