How do I write module private/protected methods in

2019-05-04 17:30发布

问题:

I understand that to write python module private/protected functions you use

def _func():
    ...

but I have an object hierarchy with specialized overrides. Also I want to hide the internal implementation(since its not meant for outside use, and so I can hopefully improve it without breaking code, not that I think anybody will use it except me). If I use

class Paragraph(Tag):
    def _method(self):
        ...

and try calling _method from a different class that subclasses Tag IntelliJ IDEA(and probably pylint/other checkers would also) give me a warning. Is there any way to fix this?

My use case is a set of markdown tag objects to generate a "Tree"-like structure that can be transformed into the correct markdown string. Each tag overrides a protected method to transform itself and the tags it contains and some override a method to check whether the sub-tags are valid(example no nested Bolds). Only the top level tag context has a public method to transform the tree.

edit:

IntelliJ IDEA warning:

access to a protected member of a class _method

回答1:

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()