我的应用程序允许用户定义对象的调度,并将它们存储为 rrule。我需要列出这些对象并显示“每日,下午 4:30”之类的内容。有什么东西可以“漂亮地格式化”一个 rrule 实例?
问问题
1320 次
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 回答