why python does not have access modifier?And what

2019-03-25 14:51发布

why python does not have Access modifier like in c#, java i.e public, private etc.what are the alternative way of encapsulation and information hiding in python.

2条回答
我只想做你的唯一
2楼-- · 2019-03-25 15:38

From Wikipedia:

[Python] has limited support for private variables using name mangling. See the "Classes" section of the tutorial for details. Many Python users don't feel the need for private variables, though. The slogan "We're all consenting adults here" is used to describe this attitude. Some consider information hiding to be unpythonic, in that it suggests that the class in question contains unaesthetic or ill-planned internals. However, the strongest argument for name mangling is prevention of unpredictable breakage of programs: introducing a new public variable in a superclass can break subclasses if they don't use "private" variables.

From the tutorial: As is true for modules, classes in Python do not put an absolute barrier between definition and user, but rather rely on the politeness of the user not to "break into the definition."

The same sentiment is described in the We are all consenting adults paragraph of The Hitchhiker’s Guide to Python!

查看更多
做个烂人
3楼-- · 2019-03-25 15:39

The alternative is to name your "private" (they are not really private in python) with identifiers that make it easy to identify that those members should not be used from outside.

For example:

class RedmineWriter:

    __server = None
    __connected = False
...
...
...

However, if the class user really wants to change these attributes he will have no problem. It is his responsability not to do that.

Look at: http://docs.python.org/2/tutorial/classes.html#tut-private

查看更多
登录 后发表回答