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.

0

2 Answers 2

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".

Sign up to request clarification or add additional context in comments.

3 Comments

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....
You didn't show how you tried to print the double underscore value. Most likely you were accessing it incorrectly.
I'm pretty sure it's right... Maybe it has something to do with python verison? I'm using 3.5.2
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.

2 Comments

I tried it, and it didn't change
Then you did somethng different.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.