Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

self

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 ?

like image 729
imoum Avatar asked Aug 27 '13 18:08

imoum


People also ask

How do you call a function with self argument in Python?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.

How do you call yourself in a function?

A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition. (function(){ console. log(Math.

What is the self argument in Python?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.

What is self in function parameter?

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.


1 Answers

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)
like image 132
Óscar López Avatar answered Oct 11 '22 12:10

Óscar López