Skip to main content
 首页 » 编程设计

python之区分外部调用的对象方法和子类调用的对象方法的约定是什么

2025年05月04日16zlslch

我知道 Python 处理私有(private)变量/成员/函数/...的大部分细节

但是,我无法决定如何区分外部使用方法或子类使用方法。

考虑以下示例:

class EventMixin(object): 
    def subscribe(self, **kwargs): 
        '''kwargs should be a dict of event -> callable, to be specialized in the subclass''' 
 
    def event(self, name, *args, **kwargs): 
        ... 
 
    def _somePrivateMethod(self): 
        ... 

在这个例子中,我想说明的是,subscribe 是一种供类/对象的外部用户使用的方法,而 event 是一种不应从外部调用的方法,而应由子类实现调用。

现在,我认为这两个部分都是公共(public) API,因此不使用任何下划线。但是,对于这种特殊情况,例如,外部 API 不使用下划线,可子类 API 使用一个下划线,私有(private)/内部 API 使用两个下划线会感觉更简洁。然而,这会变得很笨重,因为这样内部 API 就需要被调用为

self._EventMixin__somePrivateMethod() 

那么,您的约定是什么,编码方式、文档方式或其他方式?

请您参考如下方法:

use no underscores for the external API, 
one underscore for the subclassable API, 
and two underscores for the private/internal API 

这是一种合理且相对常见的做法,是的。双下划线表示实际私有(private)(与 C++ 术语中的“ protected ”相反)在实践中很少见。您永远不知道子类可能想要覆盖哪些行为,因此假设“ protected ”通常是一个不错的选择,除非有充分的理由说明与成员打交道可能特别危险。

However, that would become unwieldy because then the internal API would 
need to be invoked as self._EventMixin__somePrivateMethod() 

不,你可以只使用双下划线版本,它会被自动修改。它很丑陋,但它有效。