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. Translate these two ways to view the function calls. For example, ' '.join(things) reads
    as, “Join things with ‘ ‘ between them.” Meanwhile, join(' ', things) means, “Call join
    with ‘ ‘ and things.” Understand how they are really the same thing.

我的问题是,我很难看到它们是如何相同的?根据我的理解,第一个功能是说把事物中的任何东西都拿出来,并用”连接起来.但第二个函数(据我所知),是说使用”和东西作为参数调用连接?在定义函数时使用它们的方式有多少?我很遗憾……你们可以澄清一下吗?

最佳答案 确切地说,’.join(东西)和join(”,东西)不一定相同.但是,’.join(东西)和str.join(”,东西)是一样的.解释需要一些关于类如何在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关注的土豆,但第一个参数始终是对象本身. Python这样做是为了你可以做’.join(事情)并让它正常工作. ”是self将在函数内部的字符串,而事物是可迭代的.

”.join(things)不是调用此函数的唯一方法.您也可以使用str.join(”,things)调用它,因为它是类str的方法.和以前一样,自我将是”并且可迭代将成为事物.

这就是为什么这两种不同的方法做同样的事情是相同的:”.join(东西)是str000连接(”,东西).

点赞