+ 1
Why self is used in python? Give me explanation about that?
2 Réponses
+ 2
In object oriented programming OOP module "self" is a reference to the same class. Just like pointing at yourself and saying I or me.
In c/c++ the call it "this"
In Visual basic they call "Me"
+ 1
I guess you're talking about class methods and arguments, where we write "def method_name(self, ...):" or "self.argument = ..."
I'll try to explain on methods. Class methods can be understood as small programms designes to work with objects (class instances). Method can, for example, create or change object's properties or perform any other actions on object. Method needs to "know", which object it should perform on. For this purpose, the method's first (and sometimes the only one) agrument is "self", which is actually the name of the instance it is called on (compare with the "__main__", which we use when we need to refer to a module inside itself). So, "self" tells the method, that it should perform on the object which it was called on (curiously, but this is how it works).
From another point of view, calling the method on a sertain instance looks like "object_name.method_name(...)". Here "object_name" is actually just the variable name referred to the object. In the class this expression is converted into "method_name(object_name, ...)", i.e. the sertain object is substituted for the parameter "self".
I hope I've answered your question, good luck:)