```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)
## 調(diào)用方法修改過屬性后再次調(diào)用屬性將是被修改后的樣子。(同一個實例)
## 類里的方法私有化
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() #只能內(nèi)部訪問
print(r2.ttt()) #讓外面獲取私有屬性,只能看不能修改
print(r2._Role__eyes) #強制獲取私有屬性信息
## 類的析構(gòu)方法(在實例銷毀的時候自動調(diào)用)
def __del__(self):
print("del.....run.....")
分享名稱:類的特性、公有私有屬性和析構(gòu)
URL地址:http://chinadenli.net/article20/ppgjjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、小程序開發(fā)、網(wǎng)站排名、電子商務(wù)、ChatGPT、搜索引擎優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)