[英]I am overriding a method in HTMLCalendar class. But it gives me an error. How do I inherit this correctly?
class foo(HTMLCalendar):
def formatday(self, day, weekday, data):
if day==0
return '<td class="noday"> </td>'
else:
return '<td class="%s">%d %s</td>' % (self.cssclasses[weekday], day, data)
a = foo()
a.formatmonth(1, 2)
Whenever I try that it gives me an error saying formatday() takes exactly 4 arguments (3 given). 每当我尝试它时,它给我一个错误,说formatday()需要4个参数(3个给定)。 I am trying to overide the formatday method so that I can put some data in it. 我试图覆盖formatday方法,以便我可以在其中放入一些数据。 Can someone tell me what I am doing wrong here? 谁能告诉我这里做错了什么?
Your problem here is that formatmonth calls formatday, and you're not overriding formatmonth, so formatmonth uses the regular arguments for formatday, ie, just day and weekday. 你的问题是formatmonth调用formatday,你没有覆盖formatmonth,所以formatmonth使用formatday的常规参数,即day和weekday。
If you don't want the data there for formatmonth, then you could just give data a default value, eg: 如果你不想格式化那里的数据,那么你可以给数据一个默认值,例如:
class foo(HTMLCalendar):
def formatday(self, day, weekday, data=''):
if day==0: # note error here in original code
return '<td class="noday"> </td>'
else:
return '<td class="%s">%d %s</td>' % (self.cssclasses[weekday], day, data)
a = foo()
a.formatmonth(1, 2)
If you do want the data there, then your options depend on what that data is. 如果您确实需要数据,那么您的选项取决于数据是什么。 Is it supposed to be the same for each day in the month being formatted? 对于格式化的月份中的每一天,它应该是相同的吗? If so, then you could override formatmonth as well, or you could have the data be an instance variable, eg, take it from a self.data
that could then be set with a.data = ...
. 如果是这样,那么您也可以覆盖formatmonth,或者您可以将数据作为实例变量,例如,从self.data
,然后可以使用a.data = ...
进行设置。 If it changes for each day, you probably should have formatday get that data from somewhere else, rather than simply having it as an argument. 如果它每天都在变化,你可能应该让formatday从其他地方获取数据,而不是简单地将它作为参数。
In general, overriding a method with a method that requires extra arguments, or has some incompatible API, is dangerous. 通常,使用需要额外参数的方法覆盖方法或具有某些不兼容的API是危险的。 Anything you don't override that calls that method will break. 你没有覆盖的任何东西调用该方法将会破坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.