Categories
python

python里的下划线及私有变量

pep8里关于私有变量的说明:

In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose name starts with an underscore.
  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
  • __double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

以下是两道练习题,看看应该输出啥
1.

class Parent(object):
def __init__(self):
self.__private()
self.public()
def __private(self):
print 'Parent.__private()'
def public(self):
print 'Parent.public()'

class Child(Parent):
def __private(self):
print 'Child.__private()'
def public(self):
print 'Child.public()'

if __name__ == "__main__":
child = Child() #会输出啥?

2.

class NameMangling(object):
def __init__(self):
self._NameMangling__private() # 调用一个没有定义的函数
self.public()
def __private(self):
print 'NameMangling.__private()'
def public(self):
print 'NameMangling.public()'

if __name == "__main__":
test = NameMangling()