1. 程式人生 > >第六周練習 part1 --- 類

第六周練習 part1 --- 類

val tony 添加屬性 mha 需要 AD his UNC IT

  

 1 #
 2 class Role:
 3     def __init__(self, name, character, weapon, skills=10, life_value=10000, money=30000, level=99):
 4         # 構造函數,在實例化時做一些類的初始化工作
 5         self.name = name  # [[實例變量]](靜態屬性)【變量】,作用域是實例本身
 6         self.character = character
 7         self.weapon = weapon
 8         self.life_value = life_value  #
私有屬性——前面加兩個杠,就不能在類的外部直接訪問、更改了,類內部的方法仍可以訪問 9 self.money = money 10 self.level = level 11 self.skills = skills 12 13 def __del__(self): 14 # 析構函數,做收尾工作 15 print("%s Completely Dead" % self.name) 16 17 class Villan(Role): 18 def kill(self): 19 print
("I am Thanos") 20 21 class Avenger(Role): 22 A = "Infinity War" # [[類變量]] 23 ‘‘‘類變量與實例變量 24 類變量存儲實例共有的屬性,實例變量存儲各自特有的屬性 25 所以若實例變量中出現了和類變量同名的變量,自然是優先訪問實例變量 26 但並不通過將其設置為默認參數來給實例添加屬性,因為類變量只需要一份存儲空間 27 而實例變量則每次實例化都會占用一次存儲空間‘‘‘ 28 29 def show_info(self): 30 # 類的方法、功能(動態屬性)【方法】
31 print(‘‘‘Name: %s\nCharacter: %s\nWeapon: %s\nLife_value: %s\nMoney: %s\nSkills: %s\nLevel: %s‘‘‘ 32 % (self.name, self.character, self.weapon, self.life_value, self.money, self.skills, self.level)) 33 34 def aim_at(self, name): 35 print("Aim at %s now" %name) 36 37 def shoot(self): 38 self.money += 10 39 print("Target got shoot") 40 print("%s earned 10 bucks and now he has %s bucks" % (self.name, self.money)) 41 42 def get_shoot(self): 43 self.life_value -= 10 44 print("%s got shoot and his current life value is %s" %(self.name, self.life_value)) 45 46 def gun(self, new_weapon): 47 self.weapon = new_weapon 48 self.money -= 100 49 print("%s costs you 100 bucks and now you have %s bucks left" %(new_weapon, self.money)) 50 51 def __privatefunc(self): # 私有方法,也是在類外部不能調用,只能在內部由別的方法調用 52 pass 53 54 # 實例化過程,得到 Role 的實例 55 # c1 = Avenger(‘Lief‘, ‘GoodMan‘, ‘399式‘) 56 c2 = Avenger(Tony, IronMan, Mark 47, money=1000000000) 57 c3 = Avenger(Thor, ThunderGod, StormHammer) 58 # c4 = Avenger(‘Peter‘, ‘SpiderMan‘, ‘IronSpiderSuit‘) 59 # c5 = Avenger(‘Banner‘, ‘Hulk‘, ‘HisFists‘, skills=5) 60 # c6 = Avenger(‘Natasha‘, ‘BlackWidow‘, ‘WidowsBite‘, skills=100) 61 # c0 = Villan("Thanos", ‘滅霸‘, "Infinety Gloves") 62 # 63 c2.show_info() 64 # c1.aim_at(‘Tony‘) 65 # c1.shoot() 66 # c2.get_shoot()

第六周練習 part1 --- 類