-1

Let's say I have this class in my module:

class Person:
    def __init__(self, name):
        self._name = name

So I have in my class a protected attribute called _name but I'm still able to call this attribute like this:

p = Person('Felipe')
print(p._name)

Why? Shouldn't protected attributes be protected from direct access outside their class or subclasses?

4
  • 1
    You're looking for self.__name. Commented Jul 5, 2017 at 18:20
  • No, I'm not. I'm trying to understand WHY Python let me access protected attributes outside their class and subclasses like that Commented Jul 5, 2017 at 18:22
  • 1
    it's more about conventions, not prohibitions Commented Jul 5, 2017 at 18:22
  • 1
    Not sure what makes you think self._name is protected. Commented Jul 5, 2017 at 18:22

1 Answer 1

1

@coldspeed got it right. You need a name which starts with a double underscore if you want Python apply the "mangling" to names: it basically changes the variable name and makes it not accessible from outside.

See here and this is the official python doc

And don't forge this is Python, non Java.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.