问题
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