Inheritance¶
การสืบทอดคุณสมบัติเป็นเทคนิคการลดความซ้ำซ้อนในการเขียนข้อมูลหรือการสั่งงานซ้ำดังตัวอย่าง
แบบปกติ¶
1class Character:
2
3 def __init__(self, name='Bob', hp=100, damage=20):
4 self.name = name
5 self.hp = hp
6 self.damage = damage
7
8 def attack(self, b):
9 b.hp -= self.damage
10
11 def __repr__(self):
12 return f'Character(name={self.name}, hp={self.hp}, damage={self.damage})'
13
14class NPC(Character):
15
16 def __init__(self, location='Potion Shop'):
17 super().__init__(damage=0)
18 self.location = location
19
20 def chat(self, b):
21 print(f'chat with character {b.name}')
22
23 def __repr__(self):
24 return f'NPC(name={self.name}, hp={self.hp}, damage={self.damage}, location={self.location})'
25
26p = Character(name='Paul')
27print(p)
28
29b = NPC()
30print(b)
31
32b.chat(p)
33p.attack(b)
34print(b)
โดยใช้ dataclass¶
1from dataclasses import dataclass
2
3@dataclass
4class Character:
5 name: str = 'Bob'
6 hp: int = 100
7 damage: int = 20
8
9 def attack(self, b):
10 b.hp -= self.damage
11
12@dataclass
13class NPC(Character):
14 damage: int = 0
15 location: str = 'Potion Shop'
16
17 def chat(self, b):
18 print(f'chat with character {b.name}')
19
20p = Character(name='Paul')
21print(p)
22
23b = NPC()
24print(b)
25
26b.chat(p)
27p.attack(b)
28print(b)
Exercise¶
แยกคลาสเป็น Character, Player, NPC