Does Python have “private” variables in classes?

后端 未结 12 1853
不思量自难忘°
不思量自难忘° 2020-11-21 23:06

I\'m coming from the Java world and reading Bruce Eckels\' Python 3 Patterns, Recipes and Idioms.

While reading about classes, it goes on to say that in Py

12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 23:36

    Sorry guys for "resurrecting" the thread, but, I hope this will help someone:

    In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do the same thing like this:

    class Simple:
        def __init__(self, str):
            print("inside the simple constructor")
            self.__s = str
    
        def show(self):
            print(self.__s)
    
        def showMsg(self, msg):
            print(msg + ':', self.show())
    

    To instantiate this do:

    ss = Simple("lol")
    ss.show()
    

    Note that: print(ss.__s) will throw an error.

    In practice, Python3 will obfuscate the global attribute name. Turning this like a "private" attribute, like in Java. The attribute's name is still global, but in an inaccessible way, like a private attribute in other languages.

    But don't be afraid of it. It doesn't matter. It does the job too. ;)

提交回复
热议问题