简体   繁体   English

如何在我的子类中重新定义 append 方法?

[英]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类,从listLoggable类继承它,这样当您使用 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
  1. You can use the shortened version of super :您可以使用super的缩短版本:

     super().append(element)
  2. self.log() , not Loggable.log() . self.log() ,而不是Loggable.log()

  3. You forgot to provide the argument msg .您忘记提供参数msg

  4. 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)

output输出

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.

相关问题 如何重新定义Python类实例的type()? - How can I redefine the type() of instances of my Python class? 如何将我的方法子调用到我的 function 中? - how can I call my method child to inside my function? 如何实现参数为 Child class 的抽象方法? - How can I implement an abstract method with parameter as Child class? 如何从python中的类中的方法调用该类以重新定义变量? - how to call a the class from a method within the class in python to redefine a variable? 如何决定从父类或子类中调用子类中的重写方法? - How can I decide to call an overrided method in child class from either parent or child class? 如何在班级的方法中打印消息? - How can I print the message in my method in my class? 如何根据 class 使用的功能/方法将 append 密码设置为不同的列表? - How can I have a function/method append passwords to a different list depending on what class is using it? 如何将这些日期附加到我的数据框中? - How can I append these dates to my dataframe? 如何判断父 class 的 function 是由子 class 的类方法或实例方法调用的? - How can I tell a function of parent class is called by classmethod or instance method from child class? 如何使这些计数器装饰器对我的类方法起作用 - how can I make these counter decorator work for my in class method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM