How to generate a human-readable string that represents a rrule object?

自闭症网瘾萝莉.ら 提交于 2019-12-22 08:15:10

问题


My app allows users define scheduling on objects, and they is stored as rrule. I need to list those objects and show something like "Daily, 4:30 pm". There is something available that "pretty formats" an rrule instance?


回答1:


You simply have to provide a __str__ method and it will be called whenever something needs to render your object as a string.

For example, consider the following class:

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"

which pretty-prints itself using the __str__ method. When you run the following code against that class:

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

you see the following output:

Unknown
Monthly, 3rd of the month
Daily, 4:30pm


来源:https://stackoverflow.com/questions/9338600/how-to-generate-a-human-readable-string-that-represents-a-rrule-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!