Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用关键字为“的Python函数”;“自我”;争论中_Python_Self - Fatal编程技术网

如何使用关键字为“的Python函数”;“自我”;争论中

如何使用关键字为“的Python函数”;“自我”;争论中,python,self,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 = LeclercPar

我有一个函数,用于检索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\u list\u stores(92)
时,出现以下错误:

get_list_stores(92)
TypeError: get_list_stores() takes exactly 2 arguments (1 given)
你能帮我做些什么?

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

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

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

在类定义之外,具有名为“self”的第一个参数不会使 这很有意义——虽然,由于它不是一个关键字,所以它本身并不是一个错误

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

如果函数位于类(方法)内部,请按如下方式编写:

def get_list_stores(self, code):
self.get_listscores(92)
您必须通过类的实例调用它:

ls = LeclercScraper()
ls.get_list_stores(92)
如果它在类之外,则在编写时不要使用
self
参数:

def get_list_stores(code):
现在它可以作为一个普通函数调用(注意,我们不是通过实例调用函数,它不再是一个方法):


如果您试图在类中使用它,请按如下方式访问它:

def get_list_stores(self, code):
self.get_listscores(92)
如果您试图在类之外访问它,则需要首先创建
Leclercraper
的实例:

x = LeclercScraper()
y = x.get_listscores(92)
而且,
self
不是关键字。它只是按照约定选择的名称,用于表示类实例本身

这里有一个很好的参考:


试试
self.get\u list\u stores(92)
。这就像Java中的
this
关键字,这个函数在类定义中吗?应该是这样,但是没有多少上下文可以在类定义中调用
get\u list\u stores(92)
而不使用
NameError
。self不是关键字。是的,就像Jim说的,self不是关键字。它可以有你想要的任何名字
self
只是一个约定。它看起来需要一个字符串,而您正在传递一个int。这可能也是一个问题吗?