程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Reasons for adding self to methods in Python classes

編輯:Python

Reference resources  Python Methods in the class should be added self The reason of - cloud + Community - Tencent cloud

Python Class self What the hell is it

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved