how to use a Python function with keyword “self” in arguments

試著忘記壹切 提交于 2019-12-03 15:39:12

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.

iCodez

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?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!