gpt4 book ai didi

断言变量是 threading._Event protected 类实例

转载 作者:行者123 更新时间:2023-12-01 15:20:50 34 4
gpt4 key购买 nike

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

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

断言它是一个 protected 类实例似乎不是 Python 的。会 assert type(e) == type(threading.Event())会更好?另一个选择会更好吗?

最佳答案

看看at this answer about subclassing threading.Event .

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)

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



这在 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.
"""

关于断言变量是 threading._Event protected 类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41986033/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com