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.
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!
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
protected
in many static languages), a single leading underscore is more customary. –
Garrot What differences do access modifiers in c# and java make? If I have the source code, I could simply change the access from private to public if I want to access a member variable. It is only when I have a compiled library that access modifiers can't be changed, and perhaps they provide some useful functionality there in restricting the API. However, python can't be compiled and so sharing libraries necessitates sharing the source code. Thus, until someone creates a python compiler, access modifiers would not really achieve anything.
© 2022 - 2024 — McMap. All rights reserved.