テキストを右/左/中央に揃えたい初期パラメータに応じて、多くのテキストチャンクを出力するクラスがあります。次のような関数の代わりにメソッド オブジェクト (http://docs.python.org/py3k/tutorial/classes.html#method-objects) を使用できるかどうか疑問に思っていました
class textOutput(object):
def __init__(self):
self.justification = "left"
def justify(self,text):
if self.justification == "right":
return text.rjust(self._width)
elif self.justification == "center":
return text.center(self._width)
else:
return text.ljust(self._width)
def output(self):
for i in range(1 to 1000000):
print self.justify(i)
このような関数オブジェクトを使用したいと思います (上記の justify メソッドを置き換えます)
class textOutput(object):
def __init__(self):
self.justify = string.ljust
def output(self):
for i in range(1 to 1000000):
print self.justify(i,self._width)
def setJustification(self, justification):
if justification == "right":
self.justify = string.rjust
elif justification == "center":
self.justify = string.center
else:
self.justify = string.ljust
ただし、文字列データ型メンバーの関数オブジェクトを取得できるかどうかはわかりません。
どうすれば後者を達成できますか?(前者はパフォーマンスに反する不要なチェックが非常に多い)
ps:基本的にpython 2.5であるjythonを使用する必要があります
pps: 正当化の切り替えは、次のクラス メソッドで行われます。