带有str子类的os.path.join

JBe*_*rdo 5 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'
Run Code Online (Sandbox Code Playgroud)

和我想要的结果:

'C:\\the\\path\\some_file.txt'
Run Code Online (Sandbox Code Playgroud)

但输出\\some_file.txt无论是什么价值self.

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

Eth*_*man 0

如有疑问,请查看源代码 (Python32\Lib\ntpath.py)。相关位:

"""连接两个或多个路径名组件,根据需要插入“\”。 如果任何组件是绝对路径,则所有先前的路径组件将被丢弃。 """(添加强调)

函数的底部join尝试使用(where is )\在两个部分之间放置 a - 首先添加and (它们是纯字符串),然后通过调用将其添加到,这将再次调用...path += '\\' + bbsome_file.txt\some_file.txtPath(r'c:\the\path')Path.__add__(r'c:\the\path', r'\some_file.txt')os.path.join

您注意到\文件名上的 now 前导了吗?这就是为什么道路的最初部分会迷路。

os.path.join使用str(self)(或)进行调用self.path是有效的,因为 thenos.path.join只被调用一次而不是两次。