How do I write module private/protected methods in python?

邮差的信 提交于 2019-12-05 12:36:41

To clarify:

  • If a name starts with one underscore, it is 'protected'.
  • If a name starts with two underscores but does not end with two underscores, it is 'private'.

'Protected' is just a convention, but syntax checkers do nag about accessing them outside the class hierarchy.

'Private' is implemented by name mangling, so that the element can only be used from within the class where it was defined. The two underscores are replaced with _<name of class>__. There are tricks to circumvent this...

That said, what is the warning you get? In the example below, pylint does not warn me for using _func inside the Test class, but I do get a warning (W0212) at the last line. Did you forget to define the protected function in the base class?

class Test(object):
  ''' . '''
  def _func(self):
    ''' . '''
    raise NotImplementedError()
  def fun(self):
    ''' . '''
    self._func()

class Demo(Test):
  ''' . '''
  def _func(self):
    ''' . '''
    print 'Hi'

t = Demo()
t._func()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!