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 ?
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)
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.
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:
来源:https://stackoverflow.com/questions/18472904/how-to-use-a-python-function-with-keyword-self-in-arguments