【发布时间】:2014-11-24 23:36:20
【问题描述】:
我是asked to show how 为特殊记录器的旧栗子做一个类似单例的解决方案。费尽心思指出不做这类事情的原因,但我还是尝试了。
这样做时,我有一个静态类成员意外消失。
有了这个类声明:
epiLogger.py:
import logging
class epiLogger():
_initialised = {}
_finalised = {}
def __init__(self, name):
self.logger = logging.getLogger(name)
self.name = name
if not epiLogger._initialised.get(name):
self.logger.addHandler(logging.StreamHandler())
self.logger.setLevel(logging.INFO)
self.logger.info('** My Prologue **')
epiLogger._initialised[self.name] = True
def info(self, the_info):
self.logger.info(the_info)
print epiLogger._finalised.get(self.name)
def __del__(self):
print "destructing", self.name
if not epiLogger._finalised.get(self.name):
print "first destruction"
self.logger.info('** My Epilogue **')
epiLogger._finalised[self.name] = True
还有这些测试文件:
bar.py:
from epiLogger import *
a = epiLogger("bar")
a.info("foo!")
a.info("bar!")
a.info("party!")
test.py:
import bar
我明白了
~ mgregory$ python test.py
** My Prologue **
foo!
None
bar!
None
party!
None
destructing bar
Exception AttributeError: "'NoneType' object has no attribute '_finalised'" in <bound method epiLogger.__del__ of <epiLogger.epiLogger instance at 0x1004a48c0>> ignored
~ mgregory$
但如果我只运行 bar.py 文件:
~ mgregory$ python bar.py
** My Prologue **
foo!
None
bar!
None
party!
None
destructing bar
first destruction
** My Epilogue **
~ mgregory$
似乎一级间接导致对类本身的引用(访问类变量)变为“无”。
我尝试了一个更简单的测试用例,并没有以这种方式失败(!)
frob.py:
class frob():
_nasty_global_thingy = True
def __init__(self):
print "initialising a foo", frob._nasty_global_thingy
def __del__(self):
print "destroying a foo", frob._nasty_global_thingy
bar.py:
from frob import *
a = frob()
print a
这不会在导入 bar.py 时以同样的方式失败。
我知道这是不尝试这种事情的众多原因之一,但我还是想了解发生了什么。
【问题讨论】:
标签: python destructor static-members