坂本タクマ氏の書籍「Rubyではじめるシステムトレード」に従って、Python版のコード開発を行う。Ruby版では株式に関する情報処理をStock classを導入して実現している。Python版でも同じ機能を持つStock classとmethodを実装する。Pythonでclassを用いた経験があまりないため、まずは書籍内にあるRubyのsample codeをPythonで記述することにより、Pythonでのclassの使い方を学習する。
まずは書籍でclassとmethodの基本事項の解説に使われているTrader classを作成した。
trader.py
class Trader:
def win(self):
print("Win!")
def lose(self):
print(".....")
def win_or_lose(self, result):
if result == "win":
self.win()
elif result == "lose":
self.lose()
takuma = Trader()
takuma.win()
takuma.lose()
takuma.win_or_lose("win")
takuma.win_or_lose("lose")
これを実行すると、classが機能しmethodにより以下のように出力される。

インスタンス変数の事例であるWallet classsもPythonで記述してみた。
wallet.py
class Wallet:
def __init__(self, money):
self.money = money
def put_in(self, money):
self.money += money
def take_out(self, money):
self.money -= money
def money(self, money):
print(money)
my_wallet = Wallet(1000)
print(my_wallet.money)
my_wallet.put_in(5000)
print(my_wallet.money)
my_wallet.take_out(3000)
print(my_wallet.money)
これを実行すると、以下のようにインスタンス変数moneyの値をmethodで設定できていることが確認できる。

さらに事例として書籍で解説されているMan classを作成した。
Man.py
class Man:
def __init__(self, name):
if name:
self.name = name
else:
self.name = "Gonbei"
man1 = Man("Taro")
man2 = Man("")
print(man1.name)
print(man2.name)
nameが未設定の場合、if節によりインスタンス変数nameは”Gonbei”と設定される。

Pythonの解説書でオブジェクト指向に関する以下の概念は勉強
- クラス
- インスタンス
- インスタンス変数
- ローカル変数
- インスタンスメソッド