如何生成可读的字符串表示rrule对象?
我的应用程序允许用户为一些对象设置时间安排,这些安排会以一种叫做 rrule 的格式存储。我需要把这些对象列出来,并显示类似“每天,下午4:30”的内容。有没有什么工具可以把 rrule 的内容美化一下,让它看起来更好?
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