Python:替换日历模块中的方法
我正在尝试替换日历模块中的两种方法:
import calendar
c = calendar.HTMLCalendar(calendar.MONDAY)
def ext_formatday(self, day, weekday, *notes):
if day == 0:
return '<td class="noday"> </td>'
if len(notes) == 0:
return '<td class="%s">%d<br /></td>' % (self.cssclasses[weekday], day)
else:
return '<td class="%s">%d<br />%s</td>' % (self.cssclasses[weekday], day, notes)
def ext_formatweek(self, theweek, *notes):
if len(notes) == 0:
s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
else:
s = ''.join(self.formatday(d, wd, notes) for (d, wd) in theweek)
return '<tr>%s</tr>' % s
c.formatday = ext_formatday
c.formatweek = ext_formatweek
print c.formatmonth(2012,1,"foobar")
这不起作用 - 有人可以向我指出相关文献或指出我做错了什么吗? 我正在尝试从以下线程实现艾伦·海因斯的建议:线程 对我来说已经太晚了,我已经在这个问题上徘徊了一个多小时了。
预先感谢,
雅库布
I'm trying to replace two methods in calendar module:
import calendar
c = calendar.HTMLCalendar(calendar.MONDAY)
def ext_formatday(self, day, weekday, *notes):
if day == 0:
return '<td class="noday"> </td>'
if len(notes) == 0:
return '<td class="%s">%d<br /></td>' % (self.cssclasses[weekday], day)
else:
return '<td class="%s">%d<br />%s</td>' % (self.cssclasses[weekday], day, notes)
def ext_formatweek(self, theweek, *notes):
if len(notes) == 0:
s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
else:
s = ''.join(self.formatday(d, wd, notes) for (d, wd) in theweek)
return '<tr>%s</tr>' % s
c.formatday = ext_formatday
c.formatweek = ext_formatweek
print c.formatmonth(2012,1,"foobar")
This won't work - could somebody point me to relevant literature or point out what I'm doing wrong?
I'm trying to implement Alan Hynes suggestion from the following thread: thread
It way too late for me to think straight and I've been dancing around that problem for over an hour.
Thanks in advance,
Jakub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试替换类中的方法而不是实例中的方法。
像这样:
Try replacing the method at the class instead of the instance.
Like this:
更新以按照 Aaron 在评论中的建议使用
types.MethodType
。尝试:
请参阅 类型模块 文档。要查看失败的原因:
Updated to use
types.MethodType
as suggested by Aaron in the comments.Try:
See the types module docs. To see why it was failing:
你不想替换方法; Alan Hynes 建议对 HTMLCalendar 进行子类化:
这将创建一个新的派生类 (MyCustomCalendar),它继承所有 HTMLCalendar 的方法和属性,但定义其自己的
formatday
版本和格式周
。您可以在 Python 教程或网络上的其他地方阅读有关继承的更多信息。它是 Python(以及一般的面向对象编程)中的一个重要工具,许多库都是围绕它设计的。
You don't want to replace the methods; what Alan Hynes suggested was to subclass HTMLCalendar:
This will create a new derived class (MyCustomCalendar), which inherits all HTMLCalendar's methods and attributes, but defines its own versions of
formatday
andformatweek
.You can read more about Inheritance in the Python tutorial, or elsewhere on the web. It's an important tool in Python (and object-oriented programming in general), and many libraries are designed around it.