簡體   English   中英

如何在我的子類中重新定義 append 方法?

[英]How can i redefine append method in my child class?

實現LoggableList類,從listLoggable類繼承它,這樣當您使用 append 方法將項目添加到列表時,將向僅包含添加項目的日志發送一條消息。 我怎樣才能重新追加類方法LoggableList到的通話記錄方法Loggable在append方法內部類LoggableList類。

這是我嘗試編寫的代碼:

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. 您可以使用super的縮短版本:

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

  3. 您忘記提供參數msg

  4. 不要在Loggable.log多次調用str ,只需使用.format (或 f-string 如果使用 Python >= 3.6):

     print('{}: {}'.format(time.ctime(), msg))

在容器類型中構建子類的推薦方法是使用collections模塊中提供的抽象基類:

在列表的情況下,您應該使用collections.UserList 它允許您覆蓋否則可能很難的特殊方法。 (參見下圖所示的__setitem__覆蓋)。

在這種情況下,您不需要提供構造函數; 在調用超類的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM