Subclass `pathlib.Path` fails

后端 未结 7 1615
情歌与酒
情歌与酒 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:31

    You can subclass the concrete implementation, so this works:

    class Path(type(pathlib.Path())):
    

    Here's what I did with this:

    import pathlib
    
    class Path(type(pathlib.Path())):
        def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None):
            if encoding is None and 'b' not in mode:
                encoding = 'utf-8'
            return super().open(mode, buffering, encoding, errors, newline)
    
    Path('/tmp/a.txt').write_text("я")
    

提交回复
热议问题