How to write a module of private / protected methods in python?

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

def _func():
    ...

but I have a hierarchy of objects with specialized overrides. I also want to hide the internal implementation (since it is not intended to be used externally, and therefore I can hopefully improve it without breaking the code, and not that I think anyone will use it except me). If i use

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

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

My use case is a set of markdown tag objects to create a tree structure that can be converted to the correct markdown line. Each tag overrides the protected method to transform itself and the tags that it contains, and some override the method for validating the subtag (for example, there are no embedded bold fonts). Only the top-level tag context has a public tree conversion method.

edit:

IntelliJ IDEA Warning:

access to the protected element of the _method class

+4
source share
1 answer

To clarify:

  • If a name begins with one underscore, it is "protected."
  • , , 'private'.

"" - , .

'Private' , , . _<name of class>__. , ...

, ? pylint _func Test, (W0212) . ?

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

Source: https://habr.com/ru/post/1537073/


All Articles