1.私有屬性python
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:James Tao 4 class Role(object):#執行時以後就存在內存裏 5 6 #構造函數 7 #做用:在實例化時作一些類的初始化工做,開闢一塊內存 8 def __init__(self,name,role,weapon,life_value=100,money=15000): 9 self.name=name #實例變量(靜態屬性),做用域是實例自己,保存在實例的內存裏 10 self.role=role 11 self.weapon=weapon 12 self.__life_value=life_value #兩個下劃線,定義私有屬性 13 self.money=money 14 15 #析構函數 16 #做用:在實例釋放、銷燬的時候執行,一般用於一些收尾工做,例如,關閉一些數據庫鏈接,打開的臨時文件 17 def __del__(self):#在實例釋放的時候自動執行 18 print('%s完全死了' % self.name) 19 20 def show_status(self):#私有屬性在內部能夠訪問和修改 21 print('''name:{_name} weapon:{_weapon} life_value:{_life_value}''' 22 .format(_name=self.name,_weapon=self.weapon,_life_value=self.__life_value)) 23 24 def change_life_value(self):#私有屬性在內部能夠訪問和修改 25 self.__life_value=self.__life_value-10 26 27 def shot(self):#類的方法,功能(動態屬性) 28 print('%s is shooting...' % self.name) 29 30 def got_shot(self): 31 print('%s is getting shot...' % self.name) 32 33 def buy_gun(self,gun_name): 34 print('%s has bought %s' % (self.name,gun_name)) 35 36 role1=Role('Trump1','terrorist','AWM') 37 #print(role1.__life_value) #私有屬性在外部不能夠訪問和修改 38 role1.change_life_value() 39 role1.show_status()
結果:數據庫
2.私有方法函數
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:James Tao 4 #!/usr/bin/env python 5 # -*- coding:utf-8 -*- 6 # Author:James Tao 7 class Role(object):#執行時以後就存在內存裏 8 9 #構造函數 10 #做用:在實例化時作一些類的初始化工做,開闢一塊內存 11 def __init__(self,name,role,weapon,life_value=100,money=15000): 12 self.name=name #實例變量(靜態屬性),做用域是實例自己,保存在實例的內存裏 13 self.role=role 14 self.weapon=weapon 15 self.__life_value=life_value #兩個下劃線,定義私有屬性 16 self.money=money 17 18 #析構函數 19 #做用:在實例釋放、銷燬的時候執行,一般用於一些收尾工做,例如,關閉一些數據庫鏈接,打開的臨時文件 20 def __del__(self):#在實例釋放的時候自動執行 21 print('%s完全死了' % self.name) 22 23 def shot(self):#類的方法,功能(動態屬性) 24 print('%s is shooting...' % self.name) 25 26 def __got_shot(self):#加兩個下劃線,定義私有方法 27 print('%s is getting shot...' % self.name) 28 29 def buy_gun(self,gun_name): 30 print('%s has bought %s' % (self.name,gun_name)) 31 32 role1=Role('Trump1','terrorist','AWM') 33 #role1.__got_shot() #私有方法在外部沒法訪問