【Python基礎】クラスメソッドの作り方|オブジェクトに機能を持たせる

クラス内メソッドの作り方

クラスの中に定義した関数を メソッド と呼びます。第1引数には必ず self を書きます。

1. メソッドの定義と呼び出し

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age  = age

    def bark(self):
        print(f"{self.name}:ワンワン!")

    def info(self):
        print(f"名前:{self.name}、年齢:{self.age}歳")

dog = Dog("ポチ", 3)
dog.bark()
dog.info()
▶ 出力結果

ポチ:ワンワン!
名前:ポチ、年齢:3歳

2. 実用例:銀行口座クラス

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner   = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"入金:{amount}円 → 残高:{self.balance}円")

    def withdraw(self, amount):
        if amount > self.balance:
            print("残高不足です")
        else:
            self.balance -= amount
            print(f"出金:{amount}円 → 残高:{self.balance}円")

acc = BankAccount("田中", 10000)
acc.deposit(5000)
acc.withdraw(3000)
acc.withdraw(20000)
▶ 出力結果

入金:5000円 → 残高:15000円
出金:3000円 → 残高:12000円
残高不足です
< 前の記事__init__メソッドとselfの役割
次の記事 >継承(既存クラスの再利用)

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

上部へスクロール