我想使用“\”作为运算符实现文件路径的串联,重新定义相应的函数(如果有的话)。
例如:
path1 = '\home'
path2 = 'codes'
codepath = path1 \ path2
因此,在方法的重定义中在 path1 和 path2 之间添加 str "\",我应该断言 codepath = '\home\codes'
最佳答案
pathlib
模块支持 /
用于连接路径对象。
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
作为如何使用 __div__
的示例,这里有一个扩展 str
的简单类。只要至少一个参数是 MyPath
的一个实例,它就应该可以工作(即,它不适用于两个纯字符串)。
class MyPath(str):
def __div__(self, other):
assert isinstance(other, str)
return os.path.join(self, other)
def __rdiv__(self, other):
assert isinstance(other, str)
return os.path.join(other, self)
# Using __div__
print MyPath("/home/bob") / MyPath("bin")
print MyPath("/home/bob") / "bin"
# Using __rdiv__
print "/home/bob" / MyPath("bin")
关于python - python中有对应 "\"的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566883/