【问题标题】:Why do some libraries write private class functions only to then assign a public variable exposing them?为什么有些库只编写私有类函数然后分配一个公开它们的公共变量?
【发布时间】:2017-04-12 17:24:45
【问题描述】:

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

他们为什么这样做?

示例代码:

@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

【问题讨论】:

  • self.whatever() 被覆盖时,可能仍然可以执行self._whatever(),但很难从这里确定意图。

标签: python class decorator python-decorators


【解决方案1】:

这几乎可以肯定是 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) 装饰器函数。

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

这不是唯一的保留; Google Python styleguide on Properties 也同样陈旧,参见Google Style Guide properties for getters and setters

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 1970-01-01
    • 2011-07-22
    • 2014-09-05
    • 2012-05-29
    • 2011-12-03
    • 1970-01-01
    • 2016-11-14
    • 2011-02-23
    相关资源
    最近更新 更多