检查这个未记录的threading.Thread
子类,需要一些指导。
我对班级的作用的理解是:
"""Reload module if it's been updated since last compiled."""
代码:
class Hotswap(threading.Thread):
def __init__(self, out, mod, gen='generate', *args, **kwargs):
self.out = out # this is an output destination
self.mod = mod
self.genname = gen # this is a generator from the "mod"
self.gen = getattr(mod, self.genname)(*args, **kwargs)
self.loaded = self.current_modtime
self.args = args
self.kwargs = kwargs
threading.Thread.__init__(self)
self.daemon = True
@property
def current_modtime(self):
return os.path.getmtime(self.mod.__file__.replace("pyc", "py"))
def run(self):
while True:
if self.current_modtime != self.loaded:
log.info("Hot-swapping module: %s", self.mod.__name__)
self.mod = reload(self.mod)
self.loaded = self.current_modtime
self.gen = getattr(self.mod, self.genname)(*self.args, **self.kwargs)
self.handle(self.gen.next())
def handle(self, elem):
self.out(elem)
这是调用该类的示例:
Hotswap(InfoHandler.add, info, 'generate', info_queue, first_frame).start()
在InfoHandler创建TornadIO套接字的地方,info
是一个模块,generate
方法,info_queue, first_frame
是* args。
我不明白out, mod, gen='generate'
与threading.Thread
group=None, target=None, name=None
的关系。当threading.Thread.__init__(self)
运行时,group,target和name是否被初始化为默认值(none)?
答案 0 :(得分:1)
如果查看threading.Thread
的文档,您会看到
threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
是的,当调用超类“None
时,这些值将设置为__init__
。
__dict__
问题有点复杂。请使用以下代码(为了清楚起见,我使用与您的问题相同的名称):
class Thread(object):
def __init__(self, a=None):
self.a = a
def b(self):
pass
class Hotswap(Thread):
def __init__(self, x=None):
print("Before init: {}".format(self.__dict__))
self.x = x
super(Hotswap, self).__init__()
print("After init: {}".format(self.__dict__))
def y(self):
pass
print("On Hotswap class: {}".format(Hotswap.__dict__))
h = Hotswap()
print("On Hotswap instance: {}".format(h.__dict__))
输出将是这样的:
On Hotswap class: {'y': <function y at 0x24b9bc>, '__module__': '__main__', '__doc__': None, '__init__': <function __init__ at 0x24b97c>}
Before init: {}
After init: {'a': None, 'x': None}
On Hotswap instance: {'a': None, 'x': None}
正如您所看到的,除非您在实例上调用它,否则它不会考虑超类(或它自己的)属性。