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