python - 嵌套 class 访问修饰符

python - nested class access modifier

我试图在 __Team class 的构造函数中创建 __Profile class 的实例,但我无法访问 __Profile。我应该怎么做?

这是我的代码

class SlackApi:
    # my work
    class __Team:
        class __Profile:
            def get(self):
                # my work 
        def __init__(self, slackApi):
            self.slackApi = slackApi
            self.profile = __Profile()
            self.profile = __Team.__Profile()
            self.profile = SlackApi.__Team.__Profile()
            # I tried to all of these case, but I failed
            # I need to keep '__Team', '__Profile' class as private class

我的python版本是3.5.1

您可以这样访问:

SlackApi._SlackApi__Team._Team__Profile

或者像这样:

self._Team__Profile

但这是错误的。为了您自己的方便,不要将它们设为私有 class.

Python 没有访问修饰符。如果您尝试将 __ 视为传统的 private 访问修饰符,这就是您遇到的问题之一。前导双下划线导致名称混淆 - class Foo(或 class __FooFoo 之前的任意数量的前导下划线)中的名称 __bar 将被混淆为 _Foo__bar.

如果你真的想保留那些前导双下划线,你必须自己明确地修改名称:

self.profile = SlackApi._SlackApi__Team._Team__Profile()

这也是您从 SlackApi 外部访问 __Profile class 的方式,因此您基本上绕过了任何假装这些东西是私有的。