这两个功能如何相同?

时间:2015-11-26 00:03:18

标签: python

以下是Zed Shaw在学习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!

然后在其中一项研究演习中,他说:

  
      
  1. 翻译这两种方式来查看函数调用。例如,' '.join(things)读取   as,“在things之间加入‘ ‘。”同时,join(' ', things)表示“致电join   使用‘ ‘things。“了解它们是如何真实相同的。
  2.   

我的问题是,我很难看到他们是如何做同样的事情的?根据我的理解,第一个功能是说取things中的任何内容,并将它们与' '连接起来。但是第二个函数(据我所知)是在使用join' '作为参数时调用things?在定义函数时使用它们的方式有多少?我很遗憾......你们可以澄清一下吗?

1 个答案:

答案 0 :(得分: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) str.join('', things) override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let height = // needs to be variable let width = UIScreen.mainScreen().bounds.width return CGSize(width: width, height: height) } 为{{1}}。

相关问题