Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: User Auth | OOP Concepts
In-Depth Python OOP

book
Challenge: User Auth

Opgave

Swipe to start coding

Let's improve your User class!

  1. Create the class attribute is_authenticated in the User class.
  2. Define the login() method that takes arguments self and taken_password.
  3. The login() method should compare the user and taken passwords.
    If the user password is equal to the taken password, the True should be assigned to the is_authenticated attribute.
    If the user password is not equal to the taken password, the "Wrong password!" should be written in the console.
  4. Define the logout() methods. This method should assign the False value to the is_authenticated instance attribute.

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("User is authenticated")
else:
print("Wrong password!")

def logout(self):
self.is_authenticated = False
print("User is loggouted")

bob = User("bob123.user", "secret_bob_password")
print(bob.is_authenticated)

bob.login("123wsad123")
bob.login("secret_bob_password")

print(bob.is_authenticated)

bob.logout()
print(bob.is_authenticated)

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 8
class User:
___ = False
def __init__(self, username, password):
self.username = username
self.password = password
def ___(self, ___):
if self.___ == taken_password:
self.is_authenticated = ___
print("User is authenticated")
else:
print("Wrong password!")

def ___(self):
self.___ = False
print("User is loggouted")

bob = User("bob123.user", "secret_bob_password")
print(bob.is_authenticated) # False

bob.login("123wsad123") # Try to login with wrong password
bob.login("secret_bob_password")

print(bob.is_authenticated) # True

bob.logout()
print(bob.is_authenticated) # False
toggle bottom row
some-alt