簡體   English   中英

Python 以什么順序解析函數? (為什么 string.join(lst.append('a')) 失敗了?)

[英]In what order does Python resolve functions? (why does string.join(lst.append('a')) fail?)

string.join 是如何解析的? 我嘗試如下使用它:

import string 
list_of_str = ['a','b','c'] 
string.join(list_of_str.append('d'))

但是卻得到了這個錯誤(與 2.7.2 中的錯誤完全相同):

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/string.py", line 318, in join
    return sep.join(words)
TypeError

append 確實發生了,如果您再次嘗試加入 list_of_string,您會看到:

print string.join(list_of_string)
-->'a b c d'

這是來自 string.py 的代碼(找不到 sep 的內置 str.join() 的代碼):

def join(words, sep = ' '):
    """join(list [,sep]) -> string

    Return a string composed of the words in list, with
    intervening occurrences of sep.  The default separator is a
    single space.

    (joinfields and join are synonymous)

    """
    return sep.join(words)

這里發生了什么? 這是一個錯誤嗎? 如果這是預期的行為,它是如何解決的/為什么會發生? 我覺得我要么要學習一些關於 python 執行其函數/方法的順序的有趣信息,要么我剛剛遇到了 Python 的歷史怪癖。


旁注:當然,只要事先執行 append 就可以了:

list_of_string.append('d')
print string.join(list_of_string)
-->'a b c d'
list_of_str.append('d')

不返回新的list_of_str

方法append沒有返回值,因此返回None

為了讓它工作,你可以這樣做:

>>> import string
>>> list_of_str = ['a','b','c']
>>> string.join(list_of_str + ['d'])

雖然這不是很 Pythonic 並且不需要import string ......這種方式更好:

>>> list_of_str = ['a','b','c']
>>> ''.join(list_of_str + ['d'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM