Subclass `pathlib.Path` fails

后端 未结 7 1612
情歌与酒
情歌与酒 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条回答
  •  -上瘾入骨i
    2020-12-16 10:34

    It's work too.

    from pathlib import Path
    
    class SystemConfigPath(type(Path())):
        def __new__(cls, **kwargs):
            path = cls._std_etc()
            return super().__new__(cls, path, **kwargs)
    
        @staticmethod
        def _std_etc():
            return '/etc'
    
    name = SystemConfigPath()
    name = name / 'apt'
    print(name)
    

    Printed:

    /etc/apt
    

    @staticmethod can be replaced by @classmethod

提交回复
热议问题