Python object deleting itself

后端 未结 14 1987
一向
一向 2020-11-27 04:23

Why won\'t this work? I\'m trying to make an instance of a class delete itself.

>>> class A():
    def kill(self):
        del self


>>>          


        
14条回答
  •  隐瞒了意图╮
    2020-11-27 04:58

    A replacement implement:

    class A:
    
        def __init__(self):
            self.a = 123
    
        def kill(self):
            from itertools import chain
            for attr_name in chain(dir(self.__class__), dir(self)):
                if attr_name.startswith('__'):
                    continue
                attr = getattr(self, attr_name)
                if callable(attr):
                    setattr(self, attr_name, lambda *args, **kwargs: print('NoneType'))
                else:
                    setattr(self, attr_name, None)
            a.__str__ = lambda: ''
            a.__repr__ = lambda: ''
    
    a = A()
    print(a.a)
    a.kill()
    
    print(a.a)
    a.kill()
    
    a = A()
    print(a.a)
    

    will outputs:

    123
    None
    NoneType
    123
    

提交回复
热议问题