Reference resources Python Methods in the class should be added self The reason of - cloud + Community - Tencent cloud
The first thing is clear self Only in the methods of a class can there be , Independent functions or methods do not have to have self Of .self Required when defining methods of a class , Although it is not necessary to pass in the corresponding parameters when calling .
self Names are not required , stay python in self It's not a keyword , You can define it as a or b Or any other name , But conventions are common ( In order to unify with other programming languages , Reduce the difficulty of understanding ), Don't be different , You won't understand .
In the following example self Change it to myname No mistakes :
class Person:
def _init_(myname,name):
myname.name=name
def sayhello(myname):
print 'My name is:',myname.name
p=Person('Bill')
print p
self refer to Class instance object itself ( Be careful : Not the class itself ).
class Person:
def _init_(self,name):
self.name=name
def sayhello(self):
print 'My name is:',self.name
p=Person('Bill')
print p
In the above example ,self Point to Person
Example p
. Why not point to the class itself , The following example :
class Person:
def _init_(self,name):
self.name=name
def sayhello(self):
print 'My name is:',self.name
p1=Person('Bill')
p2 = Person('Apple')
print p1
If self Point to the class itself , So when there are multiple instance objects ,self Which one ?
summary
self You need to define , But it's automatically passed in when it's called .
self The name of is not meant to be dead , But it's better to use it as agreed self
self Always refers to the instance of the class at the time of the call .