List callbacks?

前端 未结 3 422
离开以前
离开以前 2021-01-05 00:50

Is there any way to make a list call a function every time the list is modified?

For example:

>>>l = [1, 2, 3]
>>>def          


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 01:24

    You'd have to subclass list and modify __setitem__.

    class NotifyingList(list):
    
        def __init__(self, *args, **kwargs):
            self.on_change_callbacks = []
    
        def __setitem__(self, index, value):
            for callback in self.on_change_callbacks:
                callback(self, index, value)
            super(NotifyingList, self).__setitem__(name, index)
    
    notifying_list = NotifyingList()
    
    def print_change(list_, index, value):
        print 'Changing index %d to %s' % (index, value)
    
    notifying_list.on_change_callbacks.append(print_change)
    

    As noted in comments, it's more than just __setitem__.

    You might even be better served by building an object that implements the list interface and dynamically adds and removes descriptors to and from itself in place of the normal list machinery. Then you can reduce your callback calls to just the descriptor's __get__, __set__, and __delete__.

提交回复
热议问题