如何在 python 中编写模块私有/受保护的方法? [英] How do I write module private/protected methods in python?
问题描述
我知道编写python模块私有/受保护的函数你使用
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):
...
并尝试从一个不同的类调用 _method,该类是 Tag IntelliJ IDEA 的子类(可能还有 pylint/其他检查器也会)给我一个警告.有什么办法可以解决这个问题吗?
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?
我的用例是一组 Markdown 标记对象,用于生成类似树"的结构,可以将其转换为正确的 Markdown 字符串.每个标签覆盖一个受保护的方法来转换自身和它包含的标签,并且一些覆盖一个方法来检查子标签是否有效(例如没有嵌套的粗体).只有顶级标签上下文有一个公共方法来转换树.
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.
IntelliJ IDEA 警告:
IntelliJ IDEA warning:
访问类_method 的受保护成员
access to a protected member of a class _method
推荐答案
澄清:
- 如果名称以下划线开头,则它是受保护的".
- 如果名称以两个下划线开头但不以两个下划线结尾,则它是私有的".
'Protected' 只是一个约定,但语法检查器确实会在类层次结构之外访问它们.
'Protected' is just a convention, but syntax checkers do nag about accessing them outside the class hierarchy.
'Private' 是通过名称修改实现的,因此元素只能在定义它的类中使用.两个下划线被替换为 _
.有一些技巧可以绕过这个......
'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...
也就是说,您收到的警告是什么?在下面的示例中,pylint 不会警告我在 Test 类中使用 _func,但我在最后一行收到警告 (W0212).是不是忘记在基类中定义protected函数了?
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()
这篇关于如何在 python 中编写模块私有/受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!