Search code examples
python-3.xjython

Can someone tell me the function of this "self"


I use python to insert data into MySQL, in some tutorial, I must include "self" on my function,

Def haha(self, hihi):
    Print(hihi) 

I have no idea what does it mean..


Solution

  • This function takes instance of itself as an argument. It is done when declaring methods of a class because function needs to run the method from its own particular instance. Also self needed to access or update fields of particular instance of a class. For example:

    class A:
    b = 3
    def f(self):
        self.b = 5
    

    So when you create object of type A and call method f from this object, only this object's b will become 5, but other objects of type A will have b equaling to 3. Also, when you call method, you do not pass instance of it as an argument, and can just start passing arguments starting after 'self'.