When writing a class in Python, the first parameter of each function parameter is self. At first, I didn’t care what it was for, I just knew it had to be written. Later, I became more familiar with Python, and when I looked back at the concept of self, I seemed to understand it a little bit.
First of all, it is clear that self can only be found in class methods . Independent functions or methods do not need to have self. Self is required when defining a class method, although it is not necessary to pass in the corresponding parameters when calling.
The self name is not necessary. In python, self is not a keyword. You can define it as a or b or other names, but it is a convention (in order to unify with other programming languages and reduce the difficulty of understanding). Don't be different, people won't understand.
self refers to the class instance object itself (note: not the class itself).
#In the above example, self points to the instance p of Person. Why not point to the class itself, as in the following example:
If self points to the class itself, then when there are multiple instance objects, which one does self point to?
Summary
self needs to be defined when defining, but it will be automatically passed in when called.
The name of self is not stipulated, but it is best to use self according to the convention
self always refers to the instance of the class when calling.
The above is the detailed content of What is self in Python. For more information, please follow other related articles on the PHP Chinese website!