0
1

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.

Python3 class書き方

Last updated at Posted at 2022-05-23

クラスの定義 3つのパターン

class Enemy:
class Enemy():
class Enemy(object):

クラスの初期化

呼び出された時、初めに実行される
引数にself必須

class Enemy(object):
  
  # コンストラクタ
  def __init__(self):
    print("初期化") 

enemy1 = Enemy()
# 実行結果 ⇨ 初期化

何か値を保持させたい時

__init__に引数をつける
self.引数名 = 引数名

実体化するとき、クラスに引数を与える

class Enemy(object):

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

enemy1 = Enemy("スライム")

# 実行結果 ⇨ スライム

メソッド

引数にselfが必須

class Enemy(object):

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

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

enemy1 = Enemy("スライム")
enemy1.attack()

# 実行結果 ⇨ スライムは攻撃した
0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?