2013-08-01 21 views
3

在Python 2.7.5:我如何繼承threading.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() 

我得到:

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

爲什麼?

我知道threading.Event我從中學到的一切:http://docs.python.org/2/library/threading.html?highlight=threading#event-objects

是什麼意思時,它說,threading.Event()是類threading.Event一個工廠函數??? (呃......對我來說看起來很簡單)。

+0

我剛剛發現http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python,目前正在閱讀它。 – Scruffy

回答

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

http://docs.python.org/2/library/threading.html?h說「class threading.Event」。有點誤導。我想我必須開始習慣打開實際的python源文件。我曾經發現,恐嚇,但我現在可能知道足夠多的Python,它是有幫助的。 – Scruffy