2016-11-28 16 views
2

我一直在阅读一些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 
+1

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

回答

3

这是几乎可以肯定的保持在从当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