Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Challenge: Protected Password | Encapsulation
In-Depth Python OOP

book
Challenge: Protected Password

Aufgabe

Swipe to start coding

Wow, here is our User class again! Let's protect the password!

  1. All password attributes and arguments were replaced by the placeholder (___) to help you not miss some attributes.
  2. Use the protected access modifier (_) to protect the password attribute.

Note

Arguments taken by functions should be without protected access modifier.

Lösung

class User:
is_authenticated = False
def __init__(self, username, password):
self.username = username
self._password = password
def login(self, taken_password):
if self._password == taken_password:
self.is_authenticated = True
print(f"{self.username} is authenticated")
else:
print("Wrong password!")

def logout(self):
self.is_authenticated = False
print(f"{self.username} is loggouted")


class Admin(User):
def create_content(self):
print(f"{self.username} creates the content")
def update_content(self):
print(f"{self.username} updates the content")
def delete_content(self):
print(f"{self.username} deletes the content")


frank = Admin("frank.admin", "secret.admin.pswrd")
frank.login("secret.admin.pswrd")
frank.create_content()
frank.update_content()
frank.delete_content()
frank.logout()

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 5
class User:
is_authenticated = False
def __init__(self, username, ___):
self.username = username
self.___ = ___
def login(self, taken_password):
if self.___ == taken_password:
self.is_authenticated = True
print(f"{self.username} is authenticated")
else:
print("Wrong password!")

def logout(self):
self.is_authenticated = False
print(f"{self.username} is loggouted")


class Admin(User):
def create_content(self):
print(f"{self.username} creates the content")
def update_content(self):
print(f"{self.username} updates the content")
def delete_content(self):
print(f"{self.username} deletes the content")


frank = Admin("frank.admin", "secret.admin.pswrd")
frank.login("secret.admin.pswrd")
frank.create_content()
frank.update_content()
frank.delete_content()
frank.logout()
toggle bottom row
some-alt