標籤:.sh code 沒有 自動 私人屬性 無法 mon self str
class Role(object):
country="wuxi" #公有屬性
def
init(self, name, role, weapon, life_value=100, money=15000):
self.name = name
self.role = role
self.weapon = weapon
self.life_value = life_value
self.money = money
self.__eyes = ‘good ‘#定義一個私人屬性
def shot(self): print("shooting...") print(self.__eyes)def got_shot(self): print("ah...,I got shot...") self.__eyes="heat" print(self.__eyes)def ttt(self): return self.__eyes #讓外面擷取私人屬性,只能看不能修改def buy_gun(self, gun_name): print("%s just bought %s" % (self.name,gun_name)) self.weapon=gun_name #修改公有屬性def __del__(self): print("del.....run.....")
r1 = Role(‘Alex‘, ‘police‘, ‘AK47‘) # 產生一個角色
r2 = Role(‘Jack‘, ‘terrorist‘, ‘B22‘) #產生一個角色
r2.buy_gun("核彈")
print(r2.weapon)
import time
time.sleep(5)
調用方法修改過屬性後再次調用屬性將是被修改後的樣子。(同一個執行個體)類裡的方法私人化
def shot2(self): # 定義一個方法
print("It‘s my own!")
r1.shot=shot2 # 把shut2傳r1.shut
r1.shot(r1)
公有屬性
#country="wuxi" 在類裡直接定義的屬性即是公有屬性
#執行個體裡自己重新定義公有屬性就不會去找父類裡的公有屬性,要是執行個體裡沒有定義就會去父類裡找。
print(r1.country)
print(r2.country)
r1.country="suzhou"
print(r1.country)
print(r2.country)
私人屬性
#self.eyes=‘good ‘ #定義一個私人屬性
#print(r2.eyes) #無法直接存取,直接查看。
#r2.got_shot() #只能內部訪問
#print(r2.ttt()) #讓外面擷取私人屬性,只能看不能修改
#print(r2._Role__eyes) #強制擷取私人屬性資訊
類的析構方法(在執行個體銷毀的時候自動調用)
def del(self):
print("del.....run.....")
類的特性、公有私人屬性和析構