4

私のアプリでは、ユーザーがオブジェクトのスケジューリングを定義でき、それらは rrule として保存されます。これらのオブジェクトをリストして、「毎日、午後 4 時 30 分」のように表示する必要があります。rruleインスタンスを「きれいにフォーマット」するものはありますか?

4

1 に答える 1

1

メソッドを提供するだけで、__str__何かがオブジェクトを文字列としてレンダリングする必要があるたびに呼び出されます。

たとえば、次のクラスを考えてみます。

class rrule:
    def __init__ (self):
        self.data = ""
    def schedule (self, str):
        self.data = str
    def __str__ (self):
        if self.data.startswith("d"):
            return "Daily, %s" % (self.data[1:])
        if self.data.startswith("m"):
            return "Monthly, %s of the month" % (self.data[1:])
        return "Unknown"

__str__メソッドを使用して自分自身をきれいに印刷します。そのクラスに対して次のコードを実行すると:

xyzzy = rrule()
print (xyzzy)
xyzzy.schedule ("m3rd")
print (xyzzy)
xyzzy.schedule ("d4:30pm")
print (xyzzy)

次の出力が表示されます。

Unknown
Monthly, 3rd of the month
Daily, 4:30pm
于 2015-07-31T06:10:25.027 に答える