[英]How can i redefine append method in my child class?
Implement the LoggableList
class, inheriting it from the list
and Loggable
classes, so that when you add an item to a list using the append method, a message is sent to the log consisting of just the added item.实现LoggableList
类,从list
和Loggable
类继承它,这样当您使用 append 方法将项目添加到列表时,将向仅包含添加项目的日志发送一条消息。 How can i redefine append method in class LoggableList
to call log method of Loggable
class inside append method in LoggableList
class.我怎样才能重新追加类方法LoggableList
到的通话记录方法Loggable
在append方法内部类LoggableList
类。
Here is my try to write a code:这是我尝试编写的代码:
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
You can use the shortened version of super
:您可以使用super
的缩短版本:
super().append(element)
self.log()
, not Loggable.log()
. self.log()
,而不是Loggable.log()
。
You forgot to provide the argument msg
.您忘记提供参数msg
。
Instead of calling str
so many times in Loggable.log
, just use .format
(or f-string if using Python >= 3.6):不要在Loggable.log
多次调用str
,只需使用.format
(或 f-string 如果使用 Python >= 3.6):
print('{}: {}'.format(time.ctime(), msg))
The recommended approach to subclass built in container types, is to use the abstract base classes provided in the collections
module:在容器类型中构建子类的推荐方法是使用collections
模块中提供的抽象基类:
In the case of list, you should use collections.UserList
;在列表的情况下,您应该使用collections.UserList
; it allows you to override special methods that may be difficult otherwise.它允许您覆盖否则可能很难的特殊方法。 (see override of __setitem__
illustrated below). (参见下图所示的__setitem__
覆盖)。
In this case, you do not need to provide a constructor;在这种情况下,您不需要提供构造函数; the append
method is overridden to include a call to self.log(elt)
, prior to calling the append
method of the superclass.在调用超类的append
方法之前, append
方法被覆盖以包括对self.log(elt)
调用。
import time
from collections import UserList
class Loggable:
def log(self, msg):
print(f'{str(time.ctime())}: {msg}')
class LoggableList(UserList, Loggable):
"""A list that documents its successive transformations
"""
def append(self, elt):
self.log(f'append({elt})')
super().append(elt)
def __setitem__(self, idx, elt):
self.log(f'set[{idx}] {elt}')
self.data[idx] = elt
log_list = LoggableList([1, 2, 3])
log_list.append(4)
log_list[2] = 0
log_list[3] = 'abc'
log_list.append(None)
print(log_list)
Fri Nov 13 23:33:33 2020: append(4)
Fri Nov 13 23:33:33 2020: set[2] 0
Fri Nov 13 23:33:33 2020: set[3] abc
Fri Nov 13 23:33:33 2020: append(None)
[1, 2, 0, 'abc', None]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.