###前提・実現したいこと
Python3.6でStrategyパターンを実装したい。
Strategyパターンで実装したクラスの関数をString型の文字列で返したい。
###発生している問題・エラーメッセージ
Pythonでオブジェクト指向の勉強しようと思い[1]のサイトを参考に Strategyパターンで処理内容に応じてPrinterを選べるプログラムを実装しました。 そして、print文を文字列処理関数outの外に書きたいと思っており、 関数outは文字列textを返すように書きました。 インスタンスメソッドの中では変数:textは文字列を表しております。 しかし、返り値として処理したtextを指定したところ、Noneが返ってきます return 'word'で固定文字列を返そうとしてもNoneのままです。 おそらく、名前空間やスコープの理解が足りないために起きた問題です。 このような場合に返り値を渡したい時はどのように修正すべきでしょうか?
###該当のソースコード
Python3.6
1# -*- coding: utf-8; -*- 2class ChooseStrategy(object): 3 def __init__(self, title, text, printer): 4 self.title = title 5 self.text = text 6 self.printer = printer 7 8 def output(self): 9 self.printer.output(self.title, self.text) 10 11class Printer(object): 12 def output_report(self, title, text): 13 assert False 14 return text 15 16class SimplePrinter(Printer): 17 def output(self, title, text): 18 #ここになんらかの文字列処理を書く予定 19 print(text) 20 print(type(text)) 21 return text 22 23 24class AuthPrinter(Printer): 25 def output(self, title, text): 26 if(text == 'password'): 27 print(text) 28 return text 29 30if __name__ == "__main__": 31 title = "Hi there!" 32 text = "Mr.smart, I'll give you some blocks. Regards," 33 instant_printer = ChooseStrategy(title, text, SimplePrinter()) 34 final_output = instant_printer.output() 35 print(type(final_output)) 36 print(final_output) 37
###出力結果
User$ python test_strategy.py
Mr.smart, I'll give you some blocks. Regards,
<class 'str'>
<class 'NoneType'>
None
###補足情報(言語/FW/ツール等のバージョンなど)
[1]http://doloopwhile.hatenablog.com/entry/20090627/1275175960
上記のサイトを参考に実装いたしました。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/01 10:42