我如何子类threading.Event?

时间:2013-08-01 15:44:33

标签: python subclass factory metaclass

在Python 2.7.5中:

from threading import Event

class State(Event):
    def __init__(self, name):
        super(Event, self).__init__()
        self.name = name

    def __repr__(self):
        return self.name + ' / ' + self.is_set()

我明白了:

  

TypeError:调用元类库时出错   function()参数1必须是代码,而不是str

为什么?

我所知道的关于线程的一切。事件我从http://docs.python.org/2/library/threading.html?highlight=threading#event-objects

学习

当它说threading.Event()是类threading.Event ???的工厂函数时,这是什么意思? (呃......看起来对我很平常)。

1 个答案:

答案 0 :(得分:5)

threading.Event不是一个类,它在threading.py中的功能

def Event(*args, **kwargs):
    """A factory function that returns a new event.

    Events manage a flag that can be set to true with the set() method and reset
    to false with the clear() method. The wait() method blocks until the flag is
    true.

    """
    return _Event(*args, **kwargs)

Sinse这个函数返回_Event实例,你可以继承_Event(尽管导入和使用下划线名称绝不是一个好主意):

from threading import _Event

class State(_Event):
    def __init__(self, name):
        super(Event, self).__init__()
        self.name = name

    def __repr__(self):
        return self.name + ' / ' + self.is_set()