2015-11-26 38 views
3

下面是Zed的肖在學習Python提供了硬盤的方式代碼:這兩個功能是如何相同的?

ten_things = "Apples Oranges Crows Telephone Light Sugar" 

print "Wait there's not 10 things in that list, let's fix that." 

stuff = ten_things.split(' ') 
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 

while len(stuff) != 10: 
    next_one = more_stuff.pop() 
    print "Adding: ", next_one 
    stuff.append(next_one) 
    print "There's %d items now." % len(stuff) 

print "There we go: ", stuff 

print "Let's do some things with stuff." 

print stuff[1] 
print stuff[-1] # whoa! fancy 
print stuff.pop() 
print ' '.join(stuff) # what? cool! 
print '#'.join(stuff[3:5]) # super stellar! 

然後在研究演習之一,他說:

  • 翻譯這兩種方式來查看函數調用。例如,' '.join(things)讀取 爲「加入things它們之間‘ ‘。」與此同時,join(' ', things)手段,「呼叫join‘ ‘things。」瞭解他們是如何真正的同樣的事情。
  • 我的問題是,我很難看到它們是如何是相同的東西?根據我的理解,第一個函數是表示取things中的任何內容,並將它們與' '連接起來。但第二個功能(據我所知)是說叫join,而用' 'things作爲一個參數?定義函數時你將使用它們的方式有多種?我很迷茫......你們能澄清一下嗎?

    +0

    看一下'join'函數的規格。它對兩個論點有什麼影響? – Barmar

    +1

    我想知道的主要是這個人發現一個內置'加入(delim,list)'函數的地方.... –

    +1

    我懷疑你正在看一本書的舊版(不正確)版本,查看[同一章節在線](http://learnpythonthehardway.org/book/ex38.html)。不幸的是,我似乎無法在任何地方找到勘誤表。 –

    回答

    7

    準確地說,''.join(things)join('',things)不一定是相同的。但是,''.join(things)str.join('',things)相同。這個解釋需要一些關於Python如何工作的知識。我會掩飾或忽略許多與本次討論不完全相關的細節。

    可以這樣實現一些內置的字符串類(聲明:這幾乎可以肯定是而不是它是如何實際完成的)。

    class str: 
        def __init__(self, characters): 
         self.chars = characters 
    
        def join(self, iterable): 
         newString = str() 
    
         for item in iterable: 
          newString += item #item is assumed to be a string, and += is defined elsewhere 
          newString += self.chars 
    
         newString = newString[-len(self.chars):] #remove the last instance of self.chars 
    
         return newString 
    

    好的,請注意,每個函數的第一個參數是self。這只是慣例,對於所有的Python關心可能是potatoes,但第一個參數總是對象本身。 Python這樣做,這樣你就可以做''.join(things)並讓它正常工作。 ''self將在函數內部的字符串,而things是可迭代的。

    ''.join(things)不是調用此函數的唯一方法。您也可以使用str.join('', things)來調用它,因爲它是類str的一種方法。如前所述,self將是''iterable將是things

    這就是爲什麼這兩種不同的方式來做同樣的事情是等效的:''.join(things)syntactic sugarstr.join('', things)