0

テキストを右/左/中央に揃えたい初期パラメータに応じて、多くのテキストチャンクを出力するクラスがあります。次のような関数の代わりにメソッド オブジェクト (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: 正当化の切り替えは、次のクラス メソッドで行われます。

4

2 に答える 2

1

あなたはどちらかを行うことができます

import string

ファイルの先頭で、またはを使用します

str.ljust
str.rjust
str.center

の対応する使用法の代わりにstringsetJustificationまた、現在のコードを呼び出さないでください。

于 2012-05-07T16:33:15.837 に答える
0

文字列から関数オブジェクトを取得するためのgetattrメソッドをご覧になったと思います。コードの次の行で、urのものが機能するはずです

{ self.justify = getattr(' ', 'ljust', None)}
于 2012-05-07T17:50:18.807 に答える