我一直在阅读一些 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))
这手动应用了 classmethod
和 utils.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/