简体   繁体   English

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

[英]How to call a function that has self as a parameter?

I've found some code online that may help me with a project that I'm doing, the problem is that it uses 2 parameters, one of which is self. 我在网上找到了一些代码,可能会对我正在做的项目有所帮助,问题是它使用2个参数,其中之一是self。 I don't know how to all a function like that and would be really grateful if someone could explain how. 我不知道该如何处理所有这样的功能,如果有人可以解释该方法,我将不胜感激。

Here's the code 这是代码

#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)

I just want to see the output so that I can tell whether or not I can use this code in my project 我只想查看输出,以便告诉我是否可以在项目中使用此代码

That is a method . 那是一种方法 You are looking at the source code for nltk.text , and this is ContextIndex.common_contexts() . 您正在查看nltk.text源代码 ,这是ContextIndex.common_contexts()

You need to create an instace of the ContextIndex class, then call the method on that: 您需要创建一个ContextIndex类的实例,然后在该实例上调用该方法:

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

Here common_contexts is then bound to the ci instance. 然后 common_contexts 绑定ci实例。 Calling the method then causes Python to provide a value for the self parameter; 然后,调用该方法会使Pythonself参数提供一个值; the instance on which the method was called. 调用该方法的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM