Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to implement `__setitem__` for `pathlib.Path`

As above. I made this attempt below but it throws an error: I don't know how to mutate self to get what I want.

from pathlib import Path

class P(type(Path()), Path):

    def __setitem__(self, key, value):
        fullparts = list(self.parts)
        fullparts[key] = value
        return P(*fullparts)

    def __getitem__(self, key):
        return P(self.parts[key])

p = P("folder/subfolder/file.txt")
p[1] = "haha"  # 


Desired outcome folder/haha/file.txt.

Actual outcome: object not changed!


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

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...