实现LoggableList
类,从list
和Loggable
类继承该类,以便在使用append方法向列表添加项时,只向包含所添加项的日志发送消息。
如何在类LoggableList
中重新定义append方法,以便在LoggableList
类的append方法中调用Loggable
类的log方法
下面是我尝试编写的代码:
import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
return
class LoggableList(Loggable, list):
def __init__(self, data):
super().__init__()
self.data = list(input('Please input your massage: '))
def append(self, element):
super(LoggableList, self).append(element)
Loggable.log()
return
建议使用
collections
模块中提供的抽象基类作为内置容器类型的子类:对于list,您应该使用^{} ;它允许您重写其他方法可能很困难的特殊方法。(参见下文所示的
__setitem__
覆盖)在这种情况下,您不需要提供构造函数;在调用超类的
append
方法之前,重写append
方法以包括对self.log(elt)
的调用输出
您可以使用
super
的缩短版本:self.log()
,而不是Loggable.log()
您忘记提供参数
msg
与其在
Loggable.log
中多次调用str
,只需使用.format
(如果使用Python>;=3.6,则使用f-string):相关问题 更多 >
编程相关推荐