python - How to subclass a class that has a __new__ and relies on the value of cls? -
my specific use case i'm trying subclass pathlib.path
. want able add or override functionality, want inherit of path. path has __new__
, in has:
if cls path: cls = windowspath if os.name == 'nt' else posixpath
in other words, path requires passing proper class it. problem don't know how both create class , call path.__new__
cls == path
.
i've tried many things , each 1 gives me different problem. 1 gives me attributeerror: type object 'rpath' has no attribute '_flavour'
because i'm trying override parent class.
python3:
class rpath(path): def __new__(cls, basedir, *args, **kwargs): return path.__new__(cls, *args, **kwargs) def __init__(self, basedir, *pathsegs): super().__init__() self.basedir = basedir def newfunction(self): print('something new')
and 1 gives returns path object, , hence doesn't allow me overrides.
def __new__(cls, basedir, *args, **kwargs): return path.__new__(path, *args, **kwargs)
i tried various usages of super()
, no avail.
this seems should pretty easy. missing?
update: trying accomplish? specifically, want make class rpath(basedir, *pathsegments)
:
rpath=rpath('\root\dir', 'relpath\path2\file.ext) assert rpath.basedir == '\root\dir' # true rpath.rebase('\new_basedir') assert rpath.basedir === '\newbasedir' # true # , while i'm @ assert rpath.str == str(rpath) # make str property == __str__(self)
i don't think that's going possible in usual way. if it, wouldn't work, because path doing not returning plain path either, it's returning subclass (windowspath or posixpath). overrides path won't take effect, because if able inherit path.__new__
, still return, say, windowspath, , windowspath inherits path, not custom path subclass.
it seems pathlib.path
has idiosyncratic class structure, , you'll have special work duplicate it. @ first guess, need make own subclasses of windowspath , posixpath, , make path subclass delegates instantiate 1 of instead of itself.
Comments
Post a Comment