2012-02-18 12 views
4

我的應用程序允許用戶定義對象的調度,並將它們存儲爲rrule。我需要列出這些對象並顯示「每日,下午4:30」。有什麼可用的「漂亮格式」一個rrule實例?如何生成一個表示rrule對象的可讀字符串?

+0

不,我知道的,但它會很容易寫。 – Blender 2012-02-18 04:46:30

+0

這裏有一個'__repr__'和'__str__'的好解釋 - > http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python – synthesizerpatel 2012-02-18 04:58:31

+0

@synthesizerpatel是的,我讀過它了,這很好。但是我的問題更像是如何使用'__str__'來完成,因爲它是爲最終用戶設計的。 – 2012-02-18 13:00:42

回答

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 
相關問題