1

我对Gael Varoquaux的traitsui 教程有疑问。在代码片段 7 中,他创建了一个 CaptureThread 类,用于生成用于从相机获取图像的线程。他还开设了一个相机课程。

class TextDisplay(HasTraits):
    string = String()
    view = View(Item('string', show_label=False, springy=True, style='custom'))

class CaptureThread(Thread):
    def run(self):
        #self.display is set outside the class definition by the caller
        self.display.string = 'Camera started\n' + self.display.string
        n_img = 0
        while not self.wants_abort:
            sleep(0.5)
            n_img += 1
            self.display.string = ' %d image captured\n' % n_img \
                                        + self.display.string
        self.display.string = 'Camera stopped\n' + self.display.string

class Camera(HasTraits):
    start_stop_capture = Button()
    display = Instance(TextDisplay)
    capture_thread = Instance(CaptureThread)

    view = View( Item('start_stop_capture', show_label=False))

    def _start_stop_capture_fired(self):
        if self.capture_thread and self.capture_thread.isAlive():
            self.capture_thread.wants_abort = True
        else:
            self.capture_thread = CaptureThread()
            self.capture_thread.wants_abort = False
            self.capture_thread.display = self.display
            self.capture_thread.start()

关于这段代码,我有两个问题:

1) 为什么在 Camera 类定义中,他通过调用 Instance(CaptureThread) 使 capture_thread 成为 Trait?CaptureThread 只是一个线程类,我们为什么要从中创建一个 trait 实例呢?

2) 在 CaptureThread 类中,他使用了 self.display.string 和 self.wants_abort 字段。这两个字段不是通过构造方法传入的,而是由 Camera 类在类定义之外分配的。这是最好的做法吗?因为如果 CaptureThread 的用户忘记设置这两个字段,就会发生错误。是否有一些明智的指导方针可以知道我什么时候可以分配这样的东西,或者我应该使用构造函数来分配它们?

我希望这些问题是有意义的,并且这是问他们的正确地方!谢谢,实验室迷

4

1 回答 1

2
  1. capture_thread = Instance(CaptureThread)不创建CaptureThread. 它更像是Camera在创建类时被类使用的声明。它告诉Camera该类它将有一个名为的属性,该属性capture_thread应该是CaptureThreador的实例,None并且默认为None. 此默认设置让“测试是否self.capture_thread已初始化,否则创建它”逻辑_start_stop_capture_fired()更简洁,至少符合某些人的口味。

  2. 对于threading.Thread子类,是的,这是一种惯用的方式,尽管不是唯一的方式。Thread已经有一个特定的__init__实现,你可以重写它来做其他事情,但作者在这种情况下会避免这样做是可以理解的。

    不是初始化子类的惯用方法,HasTraits实际上是使用关键字参数。

于 2013-09-11T10:36:18.430 回答