擅长:python、mysql、java
<p>如果上下文管理器是一个类,并且只有一个实例,那么您可以在堆上找到它:</p>
<pre><code>import gc
class ConMan(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print "enter %s" % self.name
def found(self):
print "You found %s!" % self.name
def __exit__(self, *args):
print "exit %s" % self.name
def find_single(typ):
single = None
for obj in gc.get_objects():
if isinstance(obj, typ):
if single is not None:
raise ValueError("Found more than one")
single = obj
return single
def foo():
conman = find_single(ConMan)
conman.found()
with ConMan('the-context-manager'):
foo()
</code></pre>
<p><em>(免责声明:不要这样做)</em></p>