我在 Python 的线程模块源代码中注意到了这一点:
def Event(*args, **kwargs):
return _Event(*args, **kwargs)
class _Event(_Verbose):
...
我是否正确地假设这是在其他语言中模仿“密封”类 (c#) 或“最终”类 (java) 的尝试?这是 Python 中的常见模式吗?在 Python 中是否有任何其他方法可以解决此问题?
最佳答案
我不喜欢这种标识符的选择。类名通常以大写字母开头,因此您认为可以说 isinstance(x, Event)
,但实际上不能。我认为像 make_event
这样明确地将函数标识为函数的名称会更好。
这个问题已经discussed在邮件列表中,BDFL states :
This started out as an experiment in API design, where I tried to make things look as much like the similar Java API as possible (I didn't want to invent yet anotherwobbly wheel). I specifically wanted these not to be classes so that people wouldn't start subclassing them. At the time PEP-8 wasn't well established (if at all) and I wanted the factory functions to look like classes. I think in 2.7 / 3.1 we can change the factory functions to conform to PEP-8 (leaving the old names in for a couple of release).
他提到的更改尚未完成,但我认为可以肯定地说,如今命名方案被视为误导,不应扩散。
当您说引入这些工厂函数是为了模仿密封类时,您说得对。 BDFL says
Allowing them to be subclassed makes it harder to replace them on some platforms with equivalent but faster implementations.
我不认为这种方案太常见。大多数时候,没有动机用等效的实现替换类,如果一个类不是为子类化而设计的,您可以在文档中提及。
关于Python 约定 : function constructor for a private class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4762384/