有誰知道爲什麼os.path.join
函數不適用於str
的子類?os.path.join與str子類
(我在Windows上使用Python3.2 x64和x86的Python2.7,結果是一樣的)
這是我的代碼有
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'
但輸出是\\some_file.txt
不管值self
。
我知道我可以做任何str(self)
或將其存儲爲self.path
和以後使用,但爲什麼os.join.path
不接受海峽子,也不產生錯誤(比如當你使用數字或任何非字符串類型)?
那麼,這就是我剛剛在我的問題中寫的...我想知道它是一個錯誤還是CPython實現或其他。順便說一句'isinstance'將在這種情況下返回True。 – JBernardo
是的,你是對的。它必須有'string .__ class __.__ name__ =='str'' –
不,解釋器不會檢查那個字符串,因爲我可以隨時更改它... – JBernardo