【问题标题】:how do i subclass threading.Event?我如何继承threading.Event?
【发布时间】:2013-08-02 15:32:08
【问题描述】:

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

我明白了:

TypeError:调用元类库时出错
function() 参数 1 必须是代码,而不是 str

为什么?

我所知道的关于 threading.Event 的一切我从:http://docs.python.org/2/library/threading.html?highlight=threading#event-objects

当它说 threading.Event() 是类 threading.Event 的工厂函数时是什么意思??? (呃......对我来说就像普通的旧实例)。

【问题讨论】:

标签: python subclass factory metaclass


【解决方案1】:

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

【讨论】:

  • docs.python.org/2/library/threading.html?h 说“类 threading.Event”。有点误导。我想我将不得不开始习惯于打开实际的 python 源文件。我曾经觉得这很吓人,但我现在可能已经知道足够多的 Python 了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 2010-12-22
  • 2010-12-08
  • 1970-01-01
相关资源
最近更新 更多