ArticleDirectory
- Why Python wants self
- Why does Python assign values to self without having to assign values to self?
- Extension
Address: http://sjolzy.cn/Why-should-self-Python.html
Since getting started with python, I have seen that the function in the class must contain a self parameter, so I have never understood the cause. 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,The class method must have an additional first parameter.(Self), But when calling this methodThis parameter does not have to be assigned a value.(Explicit and 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, get the object myobject, and then call the method of this objectMyobject. Method (arg1, arg2)In this process, python is automatically convertedMyclass. 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:
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,
Class Python:
Def selfdemo ():
Print 'python, why self? '
P = Python ()
P. selfdemo ()
The following error is reported: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