Python classes losing attributes

后端 未结 3 1692
甜味超标
甜味超标 2021-01-02 06:37

I have a peculiar python problem. During the course of execution of my gtk python application, some of my class objects mysteriously lose attributes, causing some of the fun

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 06:56

    Well you can use property and inspect module to trace changes to attribute like this:

    import sys
    import inspect
    
    def from_where_called():
        info = inspect.getframeinfo(sys._getframe(2))
        code = info.code_context[0] if info.code_context else ''
        return '%s:%s %s' % (info.filename, info.lineno, code)
    
    def add_watched_attribute(name):  
        def attr_watch_get(self):
            value = getattr(self, '_' + name, 'unset')
            print from_where_called(), name, 'is', value
            return value
    
        def attr_watch_set(self, value):
            print from_where_called(), name, 'set to', value
            setattr(self, '_' + name, value)
    
        def attr_watch_delete(self):
            print from_where_called(), name, 'deleted'
            delattr(self,'_' + name)
    
        sys._getframe(1).f_locals[name] = property(
            attr_watch_get, attr_watch_set, attr_watch_delete
        )
    
    
    class InspectedClass(object):
        add_watched_attribute('victim')
    
        def __init__(self):
            self.victim = 2
    
        def kill(self):
            del self.victim
    
    
    x = InspectedClass()
    x.victim = 'asdf'
    x.kill()
    

    Or you can use sys.settrace from this answer: https://stackoverflow.com/a/13404866/816449

提交回复
热议问题