オブジェクト指向プログラミング
オブジェクト指向プログラミング(OOP)は、データとそれを操作する関数を「オブジェクト」としてまとめる設計手法です。Pythonは完全にオブジェクト指向に対応しています。
クラスの定義
class キーワードでクラスを定義します。
python
class Dog: """犬を表すクラス""" def __init__(self, name, age): """コンストラクタ:インスタンス生成時に呼ばれる""" self.name = name # インスタンス変数 self.age = age def bark(self): """吠えるメソッド""" return f"{self.name}がワンワン吠えました!" def introduce(self): """自己紹介メソッド""" return f"私は{self.name}、{self.age}歳です。"インスタンスの生成と使用
python
# インスタンスの生成pochi = Dog("ポチ", 3)hana = Dog("ハナ", 5)# メソッドの呼び出しpochi.bark() # "ポチがワンワン吠えました!"hana.introduce() # "私はハナ、5歳です。"# インスタンス変数へのアクセスpochi.name # "ポチ"hana.age # 5特殊メソッド(マジックメソッド)
__ で囲まれた名前のメソッドを特殊メソッド(マジックメソッド)といいます。
python
class Point: """2次元点を表すクラス""" def __init__(self, x, y): self.x = x self.y = y def __str__(self): """str()で呼ばれる:人間が読みやすい形式""" return f"Point({self.x}, {self.y})" def __repr__(self): """repr()で呼ばれる:開発者向けの表示""" return f"Point(x={self.x}, y={self.y})" def __add__(self, other): """+ 演算子の定義""" return Point(self.x + other.x, self.y + other.y) def __eq__(self, other): """== 演算子の定義""" return self.x == other.x and self.y == other.y def distance_from_origin(self): """原点からの距離""" import math return math.sqrt(self.x ** 2 + self.y ** 2)p1 = Point(1, 2)p2 = Point(3, 4)print(p1) # Point(1, 2)print(p1 + p2) # Point(4, 6)p1 == Point(1, 2) # Trueクラス変数とインスタンス変数
python
class Counter: count = 0 # クラス変数(全インスタンスで共有) def __init__(self): Counter.count += 1 # インスタンス生成のたびにカウントアップ self.id = Counter.count # インスタンス変数(各インスタンス固有) @classmethod def get_count(cls): return cls.countc1 = Counter()c2 = Counter()c3 = Counter()Counter.get_count() # 3c1.id # 1c2.id # 2継承
既存のクラス(親クラス)の機能を受け継いで新しいクラス(子クラス)を作ることを継承といいます。
python
class Animal: """動物の基底クラス""" def __init__(self, name): self.name = name def speak(self): return f"{self.name}が鳴きました"class Dog(Animal): # Animal を継承 """犬クラス""" def speak(self): # メソッドのオーバーライド return f"{self.name}がワンワン!" def fetch(self): return f"{self.name}がボールを取ってきました!"class Cat(Animal): def speak(self): return f"{self.name}がニャー!"dog = Dog("ポチ")cat = Cat("タマ")dog.speak() # "ポチがワンワン!"cat.speak() # "タマがニャー!"dog.fetch() # "ポチがボールを取ってきました!"super()
super() を使って親クラスのメソッドを呼び出せます。
python
class Shape: def __init__(self, color): self.color = color def describe(self): return f"色: {self.color}"class Circle(Shape): def __init__(self, color, radius): super().__init__(color) # 親の __init__ を呼ぶ self.radius = radius def area(self): import math return math.pi * self.radius ** 2 def describe(self): return f"{super().describe()}, 半径: {self.radius}"c = Circle("赤", 5)c.describe() # "色: 赤, 半径: 5"c.area() # 78.53...練習: 銀行口座クラス
以下のメソッドを持つ BankAccount クラスを実装してください:
__init__(owner, balance=0): 口座の初期化deposit(amount): 入金withdraw(amount): 出金(残高不足の場合はエラーメッセージを返す)__str__(): 「ownerさんの口座:balance円」