how to use a Python function with keyword "self" in arguments

imoum picture imoum · Aug 27, 2013 · Viewed 44k times · Source

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 ?

Answer

Óscar López picture Óscar López · Aug 27, 2013

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)