assert变量是threading._Event受保护的类实例

时间:2017-02-01 17:32:15

标签: assert python-2.x python-multithreading

我想检查一个变量ethreading.Event的一个实例。但是,当我创建e时,它实际上创建了一个受保护的类实例threading._Event。例如:

import threading
e = threading.Event()
assert type(e) == threading.Event   # raises AssertionError
assert type(e) == threading._Event  # succeeds

断言它是受保护的类实例似乎不是pythonic。 assert type(e) == type(threading.Event())会更好吗?另一种选择会更好吗?

1 个答案:

答案 0 :(得分:0)

看看at this answer about subclassing threading.Event

  

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

这在Python 3中有所改变:

  

class Event: """Class implementing event objects. 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. The flag is initially false. """