python - 为什么有些库只编写私有(private)类函数,然后分配一个公共(public)变量来公开它们?

标签 python class decorator python-decorators

我一直在阅读一些 Google App Engine SDK 源代码,我注意到 Google 经常编写私有(private)类方法(在方法名称前加上 _),但在完成后立即在方法代码块中,他们创建一个同名的公共(public)变量,并将私有(private)方法分配给该变量。

他们为什么要这样做?

示例代码:

@classmethod
@utils.positional(3)
def _get_by_id(cls, id, parent=None, **ctx_options):
  """Returns an instance of Model class by ID.

  This is really just a shorthand for Key(cls, id, ...).get().

  Args:
    id: A string or integer key ID.
    parent: Optional parent key of the model to get.
    namespace: Optional namespace.
    app: Optional app ID.
    **ctx_options: Context options.

  Returns:
    A model instance or None if not found.
  """
  return cls._get_by_id_async(id, parent=parent, **ctx_options).get_result()
get_by_id = _get_by_id

最佳答案

这几乎肯定是 Python 还没有装饰器语法时遗留下来的。装饰器是在 Python 2.4 中引入的(请参阅 PEP 318 ),在此之前,您必须手动将装饰器函数应用于现有的、已定义的函数对象。

代码最初应该这样写:

def _get_by_id(cls, id, parent=None, **ctx_options):
  """Returns an instance of Model class by ID.

  This is really just a shorthand for Key(cls, id, ...).get().

  Args:
    id: A string or integer key ID.
    parent: Optional parent key of the model to get.
    namespace: Optional namespace.
    app: Optional app ID.
    **ctx_options: Context options.

  Returns:
    A model instance or None if not found.
  """
  return cls._get_by_id_async(id, parent=parent, **ctx_options).get_result()
get_by_id = classmethod(utils.positional(3)(_get_by_id))

这手动应用了 classmethodutils.positional(3) 装饰器函数。

通常,保留未修饰的下划线名称以便于测试。对于类方法来说,这没有多大意义,但它可能是代码库中的一种模式,在使用装饰器的任何地方都遵循。

这并不是唯一的拖延; Google Python styleguide on Properties同样过时,请参阅 Google Style Guide properties for getters and setters .

关于python - 为什么有些库只编写私有(private)类函数,然后分配一个公共(public)变量来公开它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40853623/

相关文章:

python - 在 OpenCV 中,有些方法只存在于 c++ 中,如何在 python 中做同样的事情?

python - 创建新的 DataFrame 作为其他 DataFrame 列的有序组合

python - 从 python 中的另一个文件导入类 - 我知道修复方法,但为什么原始文件不起作用?

python - 如何处理不存在的装饰器

python - 自定义 pip 安装命令未运行

c++ - 什么是静态或常量抛出错误?

javascript - 如何使用 jQuery 将重复的类添加到 DOM 对象?

python - Python 对象的唯一表示

python - 从装饰器访问函数参数

python - 从服务器获取 TCP 响应