我的Python应用程序中有一组用户创建的对象。
如果用户删除其中一个对象,仅出于错误检查的目的,我想将其标记为已删除,以便将来使用该对象的任何尝试都会导致错误。< / p>
我考虑了一些选择:
del
:这会删除引用并保留任何悬空引用。__dict__.clear()
这会在访问对象时出现令人困惑的AttributeError
,并删除可能有助于跟踪对象的所有信息我还考虑重写__getattribute__
但是,改变这似乎是无效的。
class MyClass:
def __init__( self ):
self.a = 1
self.b = 2
self.c = 3
m = MyClass()
print( m.a )
print( m.b )
print( m.c )
def fn_deleted( self, attribute ):
raise ValueError( "This object should have been deleted :(" )
m.__getattribute__ = fn_deleted
print( m.a ) # <-- NO ERROR
我觉得应该有一种简单的方法来检查悬空引用。有什么想法吗?
答案 0 :(得分:2)
class MyClass(object):
def __init__( self ):
self.a = 1
self.b = 2
self.c = 3
self.__deleted__ = dict()
def __delattr__(self, item):
value = self.__getattribute__(item)
self.__deleted__[item] = value
# optional actually delete attribute..
super().__delattr__(item)
def __getattribute__(self, item):
if item == '__deleted__':
return super().__getattribute__(item)
elif item in self.__deleted__:
print('item has been deleted, prev value: {}'.format(self.__deleted__[item]))
else:
return super().__getattribute__(item)
m = MyClass()
print( m.a )
del m.a
print( m.a )
---------------------------
1
item has been deleted, prev value: 1
None