Question

Can we simulate private and protected access specifiers in python?

Name Mangling

eg:

__var=10

can simulate private but its viable to be accessed outside easily via the object.

object._className__var

So is there a way we could simulate or does python a solution directly which I am not aware of?

Was it helpful?

Solution

Python does not have mandatory access control like some other languages you may be used to. The philosophy of the language is "We are all consenting adults".

By convention, private attributes are prefixed with an underscore, which is a hint to people that they shouldn't be used directly. But it's just that, convention. If you want to sandbox Python, you need to do it in a separate process.

The purpose of the double underscore mangling is to prevent accidental name collisions, not to enforce access control.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top