python - os.path.join 与 str 子类

标签 python string path python-3.x

有人知道为什么 os.path.join 函数不适用于 str 的子类吗?

(我在 Windows 上使用 Python3.2 x64 和 Python2.7 x86 结果是一样的)

这是我的代码

class Path(str):
    def __add__(self, other):
        return Path(os.path.join(self, other))

p = Path(r'C:\the\path')
d = p + 'some_file.txt'

以及我想要的结果:

'C:\\the\\path\\some_file.txt'

但无论 self 的值如何,输出都是 \\some_file.txt

我知道我可以执行 str(self) 或将其存储为 self.path 并稍后使用,但为什么 os.join.path 不接受 str 子类也不引发错误(例如当您使用数字或任何非字符串类型时)?

最佳答案

看起来 os.path.join 使用 __add__ 方法中的构建,这可以通过在 __add__ 中放置打印语句来验证> 方法。

>>> class Path(str):
...     def __add__(self, other):
...             print 'add'
...             return Path(os.path.join(str(self), other))
... 
>>> p = Path(r'/the/path')
>>> p + 'thefile.txt'
add
>>> class Path(str):
...     def __add__(self, other):
...             print 'add'
...             return Path(os.path.join(self, other))
... 
>>> p = Path(r'/the/path')
>>> p + 'file.txt'
add
add
# add printed twice

最简单的解决方案: 变化

return Path(os.path.join(self, other))

return Path(os.path.join(str(self), other))

有效。

关于python - os.path.join 与 str 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7682198/

相关文章:

php - 从连接到 MySQL 的 php 调用 python 脚本

string - 将后缀按后缀数组排序有何意义?

c# - 在 C# 中使用/或\\for 文件夹路径

java - 使用 File.separator 的相对路径

python - mongo 查询不返回结果

python - 填充 python 矩阵

python - 如何在我的网站上将 WMD markdown 语法转换为 HTML?

python 字符串剥离不适用于尾随双引号

c++ - 在编译时加密/混淆字符串文字

sockets - 安装 lua 套接字时出错