Python 依賴關係
阿新 • • 發佈:2018-12-27
class Person: def play(self, tools): # 通過引數的傳遞把另外一個類的物件傳遞進來 tools.run() print("很開心, 我能玩兒遊戲了") # class Computer: def run(self): print("電腦開機. 可以執行") # class Phone: def run(self): print("手機開機, 可以執行") c = Computer() phone = Phone() p = Person() p.play(phone) # 寫一個植物大戰殭屍 # 1. 植物 # 打殭屍. 殭屍掉血 # 2. 殭屍 # 吃植物. 植物掉血 class Plant: def __init__(self, name, hp, ad): # 200 self.name = name self.hp = hp self.ad = ad def attack(self, js): print("植物攻擊殭屍") js.hp -= self.ad print(f"殭屍掉血{self.ad}, 還剩下{js.hp}") class JiangShi: def __init__(self, name, hp, ad): # 1000 800 self.name = name self.hp = hp self.ad = ad def attack(self, zw): print("殭屍咬植物") zw.hp -= self.ad print(f"植物掉血{self.ad}, 還剩{zw.hp}") # 植物 wd = Plant("歪脖子豌豆", 10, 20) # 殭屍 js = JiangShi("鐵桶殭屍", 200, 1) wd.attack(js) wd.attack(js) wd.attack(js) wd.attack(js) wd.attack(js) js.attack(wd) js.attack(wd) js.attack(wd) js.attack(wd)