1

So today I asked if there's something like Protected member class in Python where many people said there's no something like lik Public Protected or Private . But I made the following code to test this:

class Vehiculo():

    def __init__(self, peso):
        self.__peso = peso

and from an outer class I did:

car = Vehiculo(10)
car.__peso = 20

and what it printed was still 10, so this is like Private, however when I changed the class variable with just one underline:

class Vehiculo():

        def __init__(self, peso):
            self._peso = peso

it printed 20 instead. Can someone clearly explain this to me? I've read a very similar post (that many consider as duplicate) but I DON'T UNDERSTAND what they say. This is exactly the Public Private behavior. And I'd like to know how to do a Protected behavior or if it's even possible.

Thanks and regads.

Wrong
  • 1,195
  • 2
  • 14
  • 38

2 Answers2

2

There is no such thing as public, private or protected in Python classes. Private methods and values are usually prefixed with an _ underscore as a convention to hint to other developers that this shouldn't be accessed directly. However, there are no mechanisms to prevent you from simply accessing those members.

The double underscore convention (__init__, __lt__, etc) is typically used by Python itself to set specific module-level or class-level variables. These are sometimes referred to as "magic methods".

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • As I mentioned, I did some test and the double underline didn't let me access that variable from other module or class unless I used a setter function.... – Wrong Oct 09 '16 at 18:34
  • You didn't show how you tried to print the double underscore value. Most likely you were accessing it incorrectly. – Soviut Oct 09 '16 at 18:36
  • I'm pretty sure it's right... Maybe it has something to do with python verison? I'm using 3.5.2 – Wrong Oct 09 '16 at 18:52
1

Attributes with a double underscore prefix are mangled, but they are not private. You can still do car._Vehiculo__peso = 20, and that will successfully set the "private" variable.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895