First, it is clear that self is only available in class methods. Independent functions or methods do not have to carry self. Self is required when defining class methods, although you do not need to input the corresponding parameters during the call.
Self names are not mandatory. in Python, self is not a keyword. You can define it as A, B, or other names, you will not understand. In the following example, there is no error in changing self to myname:
1 ClassPerson:
2Def_ Init _ (myname, name ):
3Myname. Name = Name
4DefSayhello (myname ):
5Print 'My name is:', Myname. Name
6P = person ('Bill')
7 PrintP
Self refers to the class instance object itself (Note: it is not the class itself ).
1 class person:
2 def _ init _ (self, name):
3 self. name = Name
4 def sayhello (Self):
5 Print ' my name is: ', self. name
6 P = person ( ' Bill ')
7 Print P
in the preceding example, Self point to instance P of person. Why not point to the class itself, as shown in the following example:
1 Class Person:
2 Def _ Init _ (self, name ):
3 Self. Name = Name
4 Def Sayhello (Self ):
5 Print ' My name is: ' , Self. Name
6 P = person (' Bill ' )
7 P1 = person ( ' Apple ' )
8 Print P
If Self points to the class itself, which one does self point to when there are multiple instance objects?