参考链接:https://www.pybloggers.com/2016/02/usage-of-underscores-before-and-after-function-name-in-python/
一、开头有一个下划线
Python没有真正的私有方法,所以在方法或属性开头的下划线意味着你不应该访问这个方法,因为它不是API的一部分。
实例如下
classBaseForm(StrAndUnicode):
def _get_errors(self):
"Returns an ErrorDict for the data provided for the form"
if self._errors isNone:
self.full_clean()
return self._errors
errors = property(_get_errors)
_get_errors是一个私有方法,只应该由类或者类的子类调用,而不应该在类的外部调用
二、开头有两个下划线
两个下划线的作用是提醒用户不要重写该函数
实例如下
class A(object):
def __test(self):
print"I'm test method in class A"
def test(self):
self.__test()
class B(A):
def __test(self):
print"I'm test method in class B"
a = A()
print a.test() # Output: I'm test method in class A
b = B()
print b.test() # Output: I'm test method in class A
正如我们所看到的,b.test()没有像我们所期望的那样调用B.__test()方法。基本上这是__的正确行为。因此,当你创建一个以__开头的方法时,这意味着你不希望任何人重写它,它只能从定义它的类内部访问。
三、开头和结尾各有两个下划线
此类函数为系统定义函数名,命名函数时尽量避免此类命名方式,比如__init__()