I wonder why Python does not provide access control like C ++ and Java and cannot control the visibility of functions and classes defined in the module; the function and variable defined in the class can be identified by a prefix of no less than two underscores and a suffix of no more than one underline. This class is "private.
I asked in the python Chinese mail list, at least three workaround types are available:
1. The function definition in the class to be private starts with two underscores
Class someclass:
Def pub_func (Self ):
Self. _ private_func ()
Def _ private_func (Self ):
Print 'impl'
Someclass (). pub_func ()
Someclass (). _ private_func () # attributeerror: someclass instance has no attribute '_ private_func'
2. For the function or class to be private in the module, define it to a separate module. In the package's _ init __. define _ all __in py so that it does not include this separate module
You cannot import this independent module in the global space of another module. For example, the package structure:
Util/_ init _. py
/Private. py
/Pub. py
In util/_ init _. py:
_ All __= ["pub"]
In util/private. py
Def private_func ():
Print 'private'
In util/pub. py
Def pub_func ():
Import private
Private. private_func ()
CustomerCode:
From util import *
Pub. pub_func () # OK
Private. private_func () # nameerror: Name 'private' is not defined
However, if the customer from util import private still can use the private Module
3. The code to be private can be compiled and extended in interactive languages and provided in binary
The above methods are not satisfactory. Basically, the question is, is there a need for access control in Python? Under what circumstances will there be? How should we control it if necessary?
I don't know
See also: Access Control: language and Platform