我正在尝试创建
pathlib.Path
的子类,它将在将传递的字符串路径值传递给基类之前对其进行一些操作。
class MyPath(Path):
def __init__(self, str_path):
str_path = str_path.upper() # just representative, not what I'm actually doing
super().__init__(str_path)
但是,当我尝试使用这个时:
foo = MyPath("/path/to/my/file.txt")
bar = foo / "bar"
我收到以下错误:
TypeError: unsupported operand type(s) for /: 'MyPath' and 'str'
我正在使用 Python 3.12,据我所知,它可以更好地支持子类化 Path
Path
使用 __new__
而不是 __init__
来初始化其实例。您需要覆盖 __new__
,而不是 __init__
。
这应该有效: 从路径库导入路径
class MyPath(Path):
def __new__(cls, str_path):
str_path = str_path.upper()
return super().__new__(cls, str_path)