如何在参数中使用带有关键字“self”的Python函数

时间:2013-08-27 18:29:04

标签: python self

我有一个函数可以在Python中检索一个商店列表,这个函数叫做:

class LeclercScraper(BaseScraper):
    """
        This class allows scraping of Leclerc Drive website. It is the entry point for dataretrieval.
    """
    def __init__(self):
        LeclercDatabaseHelper = LeclercParser
        super(LeclercScraper, self).__init__('http://www.leclercdrive.fr/', LeclercCrawler, LeclercParser, LeclercDatabaseHelper)


    def get_list_stores(self, code):
        """
            This method gets a list of stores given an area code

            Input :
                - code (string): from '01' to '95'
            Output :
                - stores :
                    [{
                        'name': '...',
                        'url'
                    }]

        """

当我尝试写get_list_stores(92)时,我收到此错误:

get_list_stores(92)
TypeError: get_list_stores() takes exactly 2 arguments (1 given)

你怎么能帮我这个?

3 个答案:

答案 0 :(得分:12)

如果函数是里面一个类(一个方法),请按如下所示编写:

def get_list_stores(self, code):

你必须通过该类的实例调用它:

ls = LeclercScraper()
ls.get_list_stores(92)

如果它在一个类之外,请在没有self参数的情况下编写它:

def get_list_stores(code):

现在它可以被称为普通函数(注意我们没有在实例上调用函数,它不再是一个方法):

get_list_stores(92)

答案 1 :(得分:2)

你不要随意使用“self” - 建议self成为函数的第一个参数,这些函数被编写为类中的方法。在这种情况下,当它作为一个方法被调用时,就像在

中一样
class A(object):
    def get_list_stores(self,  code):
        ...

a = A()
a.get_listscores(92)

Python会在调用时自动插入“self”参数 (它将是外部范围中名为“a”的对象)

在类定义之外,有一个名为“self”的第一个参数没有 很有道理 - 虽然,因为它不是一个关键词,它本身并不是一个错误。

在您的情况下,很可能,您尝试调用的函数是在类中定义的: 你必须将它称为类的实例的属性,然后你 只需省略第一个参数 - 就像上面的例子一样。

答案 2 :(得分:1)

如果您尝试在课程中使用它,请按以下方式访问:

self.get_listscores(92)

如果您尝试在课外访问它,则需要先创建LeclercScraper的实例:

x = LeclercScraper()
y = x.get_listscores(92)

此外,self不是关键字。它只是通过约定选择的名称来表示自身内的类实例。

这是一个很好的参考:

What is the purpose of self?

相关问题