如何调用以self为参数的函数?

How to call a function that has self as a parameter?

我在网上找到了一些代码,可以帮助我完成我正在做的项目,问题是它使用了 2 个参数,其中一个是 self。我不知道如何实现所有这样的功能,如果有人能解释如何实现,我将不胜感激。

这是代码

#code found online
def common_contexts(self, words, num=20):
    """
    Find contexts where the specified words appear; list
    most frequent common contexts first.

    :param word: The word used to seed the similarity search
    :type word: str
    :param num: The number of words to generate (default=20)
    :type num: int
    :seealso: ContextIndex.common_contexts()
    """
    if '_word_context_index' not in self.__dict__:
        #print('Building word-context index...')
        self._word_context_index = ContextIndex(self.tokens,
                                                key=lambda s:s.lower())

    try:
        fd = self._word_context_index.common_contexts(words, True)
        if not fd:
            print("No common contexts were found")
        else:
            ranked_contexts = [w for w, _ in fd.most_common(num)]
            print(tokenwrap(w1+"_"+w2 for w1,w2 in ranked_contexts))

    except ValueError as e:
        print(e)
#How I tried to call it, lines[1] is an array containing words
df=common_contexts(lines[1])
print(df)

我只是想查看输出,以便判断我是否可以在我的项目中使用此代码

那是一个方法。您正在查看 source code for nltk.text,这是 ContextIndex.common_contexts()

您需要创建 ContextIndex class 的实例,然后调用该实例的方法:

ci = ContextIndex(tokens)
df = ci.common_contexts(lines[1])

这里 common_contexts 然后 绑定 ci 实例。然后调用该方法会导致 Pythonself 参数提供一个值;调用方法的实例。