0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python class 継承とオーバーライド

Last updated at Posted at 2022-05-24

継承

BossクラスがEnemyクラスを継承しているので、Enemyクラスのメソッドが使える

class Enemy(object):

  def __init__(self, name):
    self.name = name

  def attack(self):
    print(self.name,"は攻撃した")

class Boss(Enemy):
  pass

enemy1 = Enemy("スライム")
enemy1.attack()
# スライムは攻撃した

boss = Boss("ボス")
boss.attack()
# ボスは攻撃した

オーバーライド

EnemyクラスのattackメソッドをBossクラスで上書きする

class Enemy(object):

  def __init__(self, name):
    self.name = name

  def attack(self):
    print(self.name,"は攻撃した")

class Boss(Enemy):
  def attack(self):
    print(self.name,"は強い攻撃をした")

enemy1 = Enemy("スライム")
enemy1.attack()
# スライムは攻撃した

boss = Boss("ボス")
boss.attack()
# ボスは強い攻撃をした
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?