類的特性、公有私人屬性和析構

來源:互聯網
上載者:User

標籤:.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.....")

類的特性、公有私人屬性和析構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.