Does Python have “private” variables in classes?

后端 未结 12 1842
不思量自难忘°
不思量自难忘° 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:43

    There is a variation of private variables in the underscore convention.

    In [5]: class Test(object):
       ...:     def __private_method(self):
       ...:         return "Boo"
       ...:     def public_method(self):
       ...:         return self.__private_method()
       ...:     
    
    In [6]: x = Test()
    
    In [7]: x.public_method()
    Out[7]: 'Boo'
    
    In [8]: x.__private_method()
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
     in ()
    ----> 1 x.__private_method()
    
    AttributeError: 'Test' object has no attribute '__private_method'
    

    There are some subtle differences, but for the sake of programming pattern ideological purity, its good enough.

    There are examples out there of @private decorators that more closely implement the concept, but YMMV. Arguably one could also write a class defintion that uses meta

提交回复
热议问题