防止Visual Studio代码或IDE泄露Python类私有方法

人气:517 发布:2022-10-16 标签: methods python private ide visual-studio-code

问题描述

我只想问一个简短的问题;

从本质上讲,我想知道是否有可能从Visual Studio代码或其他IDE提供的建议列表中隐藏Python类私有方法。

例如,假设我们有一个类"A"

# Creating a class
class A:

    # Declaring public method
    def fun(self):
        print("Public method")

    # Declaring private method
    def __fun(self):
        print("Private method")
    
    # Calling private method via
    # another method
    def Help(self):
        self.fun()
        self.__fun()

现在,我们不希望Visual Studio代码或其他IDE在IDE提供的建议列表中显示"__fun"方法,我们如何才能做到这一点?

我可以看到,即使"__fun"已在类"A"中声明为私有方法,但Visual Studio代码仍会在其代码片段中提示它:

是否有可能摆脱这一点?

推荐答案

我可能找到了您问题的部分解决方案,这可能会有帮助

vscode中有一个Python语言设置,如果启用该设置,将报告在类外部使用"Protected"函数(以下划线开头)。

按CTRL+SHIFT+P,键入&q;配置语言特定设置,然后选择Python。在JSON对象中添加以下属性:

"python.analysis.diagnosticSeverityOverrides": {
    "reportPrivateUsage": "error"
}

来源:code.visualstudio.com/docs/python/settings-reference

982