繁体   English   中英

如何生成表示rrule对象的人类可读字符串?

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

我的应用程序允许用户定义对象的调度,并将它们存储为rrule。 我需要列出这些对象并显示类似“每日,下午4:30”的内容。 有一些东西可以“漂亮地格式化”一个rrule实例吗?

您只需提供__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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM