コンストラクタ
__init__という名前のメソッドはコンストラクタと呼ばる特殊メソッドであり、インスタンスを生成した際に一度だけ実行される。インスタンスの初期化を目的として利用される。
code:constructor1.py
class Myclass:
def __init__(self):
print('# コンストラクタが実行されました')
m1 = Myclass() # 引数無し
インスタンス生成時にコンストラクタに引数を与えることができる。
code:constructor2.py
class Myclass:
def __init__(self, a):
print('# コンストラクタが実行されました')
print('# 受け取った引数', a)
m1 = Myclass(1)
複数の引数を渡す例
code:constructor3.py
class Myclass:
def __init__(self, a, b, c):
print('# コンストラクタが実行されました')
print('# 受け取った引数', a, b, c)
m1 = Myclass(1, 3.14, 'moji')
/icons/hr.icon
※ ブラウザのバックボタンで戻る