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

A detailed explanation of the meaning of self in Python object-oriented programming (class programming) (a simple and clear explanation of the essence)

編輯:Python

The following is what bloggers think is right self Materials that have been explained thoroughly and concisely .






The above information makes this question simple and clear , Let's look at it carefully and believe it is right self Have a deep understanding .
To sum up :
stay Python For object-oriented programming , When a member function is called , Whether the function has parameters or not , There will be a parameter passed to it , This parameter is the class itself , So when we define a member function, whether or not there is parameter passing , Write a parameter , This parameter represents the class itself , With this parameter, we can reference the member variables and member functions of the class .
This parameter is usually named self, Of course you can also write other names , But for the standard and readability of the code , This is not recommended .
therefore , The following code :

class Staff: # Staff For the employees 
bonus = 30000 # bonus For allowance 、 Bonus means 
def salary(self): # salary It means salary 
salary = 10000+self.bonus
return salary
zhang_san = Staff()
zhang_san_salray = zhang_san.salary()

We can also write as :

class Staff: # Staff For the employees 
bonus = 30000 # bonus For allowance 、 Bonus means 
def salary(swh): # salary It means salary 
salary = 10000+swh.bonus
return salary
zhang_san = Staff()
zhang_san_salray = zhang_san.salary()

The code above , It must work correctly , As shown in the figure below :


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