答案 0 :(得分:2)
如果要限制数据模型的输入,可以使用数据模型的高级部分。
您还可以通过事件部分或数据验证部分进行数据验证。使用第一个脚本来实现小脚本,使用第二个脚本将规则硬编码到应用程序中。
In [1]: class MyObject:
pass
In [2]: obj = MyObject()
In [3]: # now lets try deleting the object
# First, create a weak reference to obj, so we can know when it is truly deleted.
from weakref import ref
from sys import getrefcount
r = ref(obj)
print("the weak reference looks like", r)
print("it has a reference count of", getrefcount(r()))
# this prints a ref count of 2 (1 for obj and 1 because getrefcount
# had a reference to obj)
del obj
# since obj was the only strong reference to the object, it should have been
# garbage collected now.
print("the weak reference looks like", r)
the weak reference looks like <weakref at 0x7f29a809d638; to 'MyObject' at 0x7f29a810cf60>
it has a reference count of 2
the weak reference looks like <weakref at 0x7f29a809d638; dead>
In [4]: # lets try again, but this time we won't print obj, will just do "obj"
obj = MyObject()
In [5]: print(getrefcount(obj))
obj
2
Out[5]: <__main__.MyObject at 0x7f29a80a0c18>
In [6]: # note the "Out[5]". This is a second reference to our object
# and will keep it alive if we delete obj
r = ref(obj)
del obj
print("the weak reference looks like", r)
print("with a reference count of:", getrefcount(r()))
the weak reference looks like <weakref at 0x7f29a809db88; to 'MyObject' at 0x7f29a80a0c18>
with a reference count of: 7
In [7]: # So what happened? It's that Out[5] that is keeping the object alive.
# if we clear our Out variables it should go away...
# As it turns out Juypter keeps a number of its own variables lying around,
# so we have to reset pretty everything.
In [8]: def my_reset(*varnames):
"""
varnames are what you want to keep
"""
globals_ = globals()
to_save = {v: globals_[v] for v in varnames}
to_save['my_reset'] = my_reset # lets keep this function by default
del globals_
get_ipython().magic("reset")
globals().update(to_save)
my_reset('r') # clear everything except our weak reference to the object
# you would use this to keep "thing" around.
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
In [9]: print("the weak reference looks like", r)
the weak reference looks like <weakref at 0x7f29a809db88; dead>