how do i subclass threading.Event?

北慕城南 提交于 2019-12-07 12:25:46

问题


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).


回答1:


threading.Event is not a class, it's function in 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 this function returns _Event instance, you can subclass _Event (although it's never a good idea to import and use underscored names):

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


来源:https://stackoverflow.com/questions/17998651/how-do-i-subclass-threading-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!