3

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?

deeshank
  • 4,286
  • 4
  • 26
  • 32

1 Answers1

6

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.

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • Thank you @Antimony. I am aware that name mangling is used to enforce access control. btw my question is how to we simulate access restrictions that is why the post :p – deeshank Jun 22 '13 at 03:00
  • 2
    The answer is you don't. You can use reflection hacks to sort of simiulate it, but you can use reflection to get around such hacks just as easily. The real question is what you are trying to acheive? – Antimony Jun 22 '13 at 03:04