類的繼承:子類繼承父類的屬性和方法


 1 class Monster:
 2     def __init__(self, hp=200):
 3         self.hp = hp
 4 
 5     def run(self):
 6         print('移動到某個位置')
 7 
 8 
 9 class Animals(Monster):  # 定義Monster的一個子類
10     def __init__(self, hp=50):
11         super().__init__(hp)  # 繼承父類的屬性
12 
13 
14 class Boss(Monster):
15     def __init__(self, hp=1000):
16         super().__init__(hp)
17 
18     def run(self):  # 與父類的方法重名,那么就只用當前的方法;類似局部變量
19         print('I am the boss, get away!')
20             
21 
22 m1 = Monster(150)
23 m1.run()
24 print(m1.hp)
25 a1 = Animal(50)
26 a1.run()  # 調用父類的方法
27 b1 = Boss(800)
28 print(b1.hp)
29 b1.run()
30 print('m1的類別:', type(m1))
31 print('a1的類別:', type(m1))
32 # 下面判斷子類關系
33 print(isinstance(b1, Monster))  # True
34 # 之前學習的數字、字符串、元組等都是類,而是都是object的子類
35 print(type(‘123’))
36 print(isinstance(['1', '2'], object))  # True

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM