3

In 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()

I get:

TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str

Why?

Everything I know about threading.Event I learned from: http://docs.python.org/2/library/threading.html?highlight=threading#event-objects

What does it mean when it says that threading.Event() is a factory function for the class threading.Event ??? (Uhh... just looks like plain old instanciation to me).

4

1 回答 1

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)

因为这个函数返回 _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()
于 2013-08-01T15:53:55.150 回答