Data Hiding in Python Class

后端 未结 4 1380
半阙折子戏
半阙折子戏 2021-01-02 09:07

I know that the attributes of class which are declared by double underscore __ prefix may or may not visible outside the class definition. As we can still acces

4条回答
  •  情深已故
    2021-01-02 09:37

    Yes, it is possible to hide private data in a closure -- at least, if there is a way to access private from outside make_A, I haven't found it:

    def make_A():
        private = {
            'a' : 1,
            'b' : 2,
            'z' : 26,
            }
        class A:
            def __init__(self):
                self.catch = 100
                private['a'] = 2    # you can modify the private data
            def foo(self):
                print(private['a']) # you can access the private data 
        return A
    
    A = make_A()
    
    a=A()
    
    a.foo()
    # 2
    

    Notice that private is not in dir(a)

    print('private' in dir(a))
    # False
    

    Although this is possible, I do not think this is recommendable way to program in Python.


    Above, private is shared by all instances of A. To use private data on a per-instance basis, add self to the dict key:

    def make_A():
        private = {}
        class A:
            def __init__(self):
                self.catch = 100
                private[self,'a'] = 1    # you can modify the private data
                private[self,'b'] = 2    
                private[self,'z'] = 26    
            def foo(self):
                print(private[self,'a']) # you can access the private data 
        return A
    

提交回复
热议问题