23

i have a function that retrieve a list of stores in Python this functions is called :

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'
                    }]

        """

when i try to write get_list_stores(92) i get this error :

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

how can you help me with this ?

imoum
  • 405
  • 3
  • 6
  • 13

3 Answers3

41

If the function is inside a class (a method), write it like this:

def get_list_stores(self, code):

And you have to call it over an instance of the class:

ls = LeclercScraper()
ls.get_list_stores(92)

If it's outside a class, write it without the self parameter:

def get_list_stores(code):

Now it can be called as a normal function (notice that we're not calling the function over an instance, and it's no longer a method):

get_list_stores(92)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
5

You don't use "self" arbitrarily - self is recommended to be the first parameter to functions which are written to be methods in classes. In that case, when it is invoked as a method, like in

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

a = A()
a.get_listscores(92)

Python will insert the "self" parameter automatically on the call (and it will be the object named "a" in the outer scope)

Outside of class definitions, having a first parameter named "self" does not make much sense - although, as it is not a keyword it is not an error per se.

In your case, most likely,t he function you are trying to call is defined in class: you have to call it as an attribute of an instance of the class, and then you simply omit the first parameter - just like in the example above.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
4

If you are trying to use it in the class, access it like this:

self.get_listscores(92)

If you are trying to access it outside of the class, you need to first create an instance of LeclercScraper:

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

Also, self is not a keyword. It is simply the name chosen by convention to represent a class instance within itself.

Here's a good reference:

What is the purpose of self?

Community
  • 1
  • 1