Python 约定 : function constructor for a private class

标签 python design-patterns

我在 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/

相关文章:

java - 多次调用同一方法时取消方法调用

python - matplotlib imshow 插值灰色边缘

python - 比较python中的字符串以查找错误

Python Pandas 在函数中处理数据帧

c# - 如何创建仅在插件可用时才调用函数的插件机制?

wpf - WPF 中使用的设计模式

python - 如何将整数数据表(来自 Python 数据表库)正确转换为 pandas Dataframe

python - 如何从 IoT Edge 自定义模块 (python) 中获取设备名称

javascript - 如果大部分功能的执行以输入为条件,那么哪一个是更好的实现方式?

ruby-on-rails - 当 Rails 应用程序变得太大时该怎么办?