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

book
Challenge: Protected Password

Uppgift

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ösning

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()

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 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()

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt