Python:Pythonのクラスとオブジェクト(OOP):__init__、メソッド、self
Python•OOPの基本

Pythonのクラスとオブジェクト(OOP):__init__、メソッド、self

Pythonのオブジェクト指向プログラミング(OOP)は、クラス、属性、メソッド、コンストラクタ初期化(__init__)を用いて現実のシステムをモデル化します。

構文

class ClassName: def __init__(self, attribute): self.attribute = attribute def method(self): # instance method

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
selfInstance Referenceメソッドを呼び出している具体的なオブジェクトインスタンスを指します。
__init__Constructor Method新しいオブジェクトが生成された際に状態を初期化します。

そのまま実行できるコード例

Compilra で実行可能

Python をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

# Python OOP: BankAccount Class
class BankAccount:
    """Represents a checking/savings account with balance validation."""
    def __init__(self, account_holder: str, initial_deposit: float = 0.0):
        self.holder = account_holder
        self.balance = initial_deposit

    def deposit(self, amount: float) -> float:
        if amount > 0:
            self.balance += amount
            print(f"Deposited ${amount:.2f}. New Balance: ${self.balance:.2f}")
        return self.balance

    def withdraw(self, amount: float) -> bool:
        if 0 < amount <= self.balance:
            self.balance -= amount
            print(f"Withdrew ${amount:.2f}. Remaining: ${self.balance:.2f}")
            return True
        print(f"Withdrawal failed: insufficient funds for ${amount:.2f}!")
        return False

# Create instance and test methods
account = BankAccount("Sarah Conner", 500.0)
account.deposit(250.0)
account.withdraw(100.0)
account.withdraw(900.0)
期待される出力:
Deposited $250.00. New Balance: $750.00
Withdrew $100.00. Remaining: $650.00
Withdrawal failed: insufficient funds for $900.00!

動作のしくみ: ステップ解説

  • 4〜6行目: __init__ が口座名義と初期残高を self に紐づけます。
  • 8〜12行目: deposit() メソッドが self.balance を更新し、取引状況を出力します。
  • 14〜20行目: withdraw() が残高不足を防ぎつつ有効な金額を引き落とします。

重要ポイント

  • インスタンスメソッドでは、呼び出し元オブジェクトに紐づけるため第1引数を self にする必要があります。
  • ClassName() をインスタンス化すると __init__() が自動的に実行されます。
  • self に設定された属性はインスタンス固有であり、他のインスタンスから独立しています。

よくある間違い: クラスメソッドの第1引数として self を省略すること

Pythonはインスタンスメソッドの第1引数としてインスタンス自身を自動的に渡します。

❌ 誤り
class User:
    def greet(): # TypeError: greet() takes 0 positional arguments but 1 was given
        print("Hi")
✅ 正しい例
class User:
    def greet(self):
        print("Hi")

関連するPythonチュートリアルとコンパイラ

Compilra で Python を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。