Python: Missing access control?

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.