-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?

flpn
  • 1,868
  • 2
  • 19
  • 31

1 Answers1

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.

FrankBr
  • 886
  • 2
  • 16
  • 37