This article mainly introduces why self is used in Python. This article explains why Python wants self and why Python assigns values to self without having to assign values to self? For more information, see Python. the Function in the class must contain a self parameter. In the evening, I checked the Python self for details.
Why Python wants self
There is an obvious difference between the methods of Python classes and common functions. in the class method, there must be an additional first parameter (self ), however, you do not need to assign a value to this parameter when calling this method (explicitly better than implicit ). The special parameter of the method of the Python class refers to the object itself. according to the Python convention, it is represented by self. (Of course, we can also use any other name, but we recommend that you use self as the standard)
Why does Python assign values to self without having to assign values to self?
Example: create a class MyClass, instantiate MyClass to get the object MyObject, and then call this object method MyObject. method (arg1, arg2). in this process, Python is automatically converted to Myclass. mehod (MyObject, arg1, arg2)
This is the principle of Python self. Even if your class method does not require any parameters, you still need to define a self parameter for this method, although we do not need to assign a value to this parameter during the instantiation call.
Instance:
The code is as follows:
Class Python:
Def selfDemo (self ):
Print 'python, why self? '
P = Python ()
P. selfDemo ()
Output: Python, why self?
Put p. selfDemo () with a parameter such as p. selfDemo (p) to get the same output.
If self is removed,
The code is as follows:
Class Python:
Def selfDemo ():
Print 'python, why self? '
P = Python ()
P. selfDemo ()
In this case, the following error occurs: TypeError: selfDemo () takes no arguments (1 given)
Extension
Self is not a keyword in Python. Self indicates the address of the current object. Self can avoid global variables caused by Unlimited' calls.
Do I know whether to hide self after Python3? It seems that all methods in the Python class must contain self, which is a little rigid.
End