← All lessons

Encapsulation

Sign in · Sign up

Lesson 10.5

Some of an object's data is better left alone from outside. In Python an underscore says so:

class User:
    def __init__(self, name, password):
        self.name = name
        self.__password = password

    def check(self, password):
        ...                    # compare with the hidden password
  • self._hp is "internal": an agreement to keep off, but still reachable;
  • self.__password has its class name mangled inside: from outside user.__password raises an AttributeError, while inside the class self.__password works;
  • hidden data is accessed through a method: user.check("python123").

The protection here is an agreement, not a lock: user._User__password still reaches the value. The point is the signal: "this is internal".

The check gives name, the password password and the list of attempts attempts. Print the name, and then Correct for the right password and Wrong for the others.

Hint

A name with two underscores in front of it (__) cannot be reached from outside.

The check method compares the passed value with the hidden field through self. Passing that field from outside gives an AttributeError, so a method is needed.