The first thing to be clear is that self is only available in the methods of the class, and independent functions or methods do not have to have the. Self is necessary when defining a method of a class, although it is not necessary to pass in the appropriate arguments when calling.
Self name is not necessary, in Python, self is not a keyword, you can be defined as a or B or other names can be, but the agreement idiomatic, do not engage in alternative, we will not understand. The following example changes self to myname without errors:
1 class Person:
2 def _init_ (myname,name):
3 Myname.name=name
4 def sayhello (myname):
5 print ' My name is: ', myname.name
6 P=person (' Bill ')
7 Print P
Self refers to the class instance object itself (note: 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
在上述例子中,self指向Person的实例p。 为什么不是指向类本身呢,如下例子:
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, then when there are multiple instance objects, which one does it point to?
Self of Python (go)