python 2018.7.24 類空間,對象空間,查詢順序 ,組合

來源:互聯網
上載者:User

標籤:__init__   找不到   OLE   靜態變數   裝備   EAP   多少   ...   屬性   

查詢順序:
對象.屬性 : 先從對象空間找,如果找不到,再從類空間找,再找不到,再從父類找....
類名.屬性 : 先從本類空間找,如果找不到,再從父類找....
對象與對象之間是互相獨立的.

計算一個類 執行個體化多少對象.
    class Count:
count = 0
def __init__(self):
Count.count = self.count + 1
obj1 = Count()
obj2 = Count()

print(Count.count)
count = 0

class Count:
count = 0
def __init__(self):
pass

通過類名可以更改我的類中的靜態變數值
Count.count = 6
print(Count.__dict__)

但是通過對象 不能改變只能引用類中的靜態變數

obj1 = Count()
print(obj1.count)
obj1.count = 6



組合: 給一個類的對象封裝一個屬性,這個屬性是另一個類的對象.

 版本二:
class GameRole:
def __init__(self, name, ad, hp):
self.name = name
self.ad = ad
self.hp = hp

def attack(self,p):
p.hp = p.hp - self.ad
print(‘%s 攻擊 %s,%s 掉了%s血,還剩%s血‘ %(self.name,p.name,p.name,self.ad,p.hp))

def armament_weapon(self,wea):
self.wea = wea


class Weapon:
def __init__(self,name,ad):
self.name = name
self.ad = ad
def fight(self,p1,p2):
p2.hp = p2.hp - self.ad
print(‘%s 用%s打了%s,%s 掉了%s血,還剩%s血‘\
% (p1.name,self.name,p2.name,p2.name,self.ad,p2.hp))

p1 = GameRole(‘大陽哥‘,20,500)
p2 = GameRole(‘印度阿寧‘,50,200)
axe = Weapon(‘三板斧‘,60)
broadsword = Weapon(‘屠龍寶刀‘,100)
# print(axe)
p1.armament_weapon(axe) # 給大陽哥 裝備了三板斧這個對象.
# print(p1.wea)
# print(p1.wea.name)
# print(p1.wea.ad)
p1.wea.fight(p1,p2)
 




python 2018.7.24 類空間,對象空間,查詢順序 ,組合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.