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

book
Challenge: AuthMixin

Uppgift

Swipe to start coding

Let's make your code more flexible.

  1. Define the AuthMixin class.
  2. Cut the login and logout methods from the User class and insert them into the AuthMixin body.
  3. Move the is_authenticated class attribute to the AuthMixin.
  4. Inherit the User class from the AuthMixin.

Note

After performing all the actions, you will have an authorization mixin (AuthMixin) that can be used for different user classes.

Lösning

class AuthMixin:
is_authenticated = False
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 User(AuthMixin):
def __init__(self, username, password):
self.username = username
self.password = password
@property
def password(self):
return self._password

@password.setter
def password(self, new_password):
if isinstance(new_password, str):
if len(new_password) >= 8:
self._password = new_password
else:
print("The password length should be >= 8.")
else:
print("The password should be string.")


class Admin(User):

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 3
single

single

class ___:
# Insert code here


class User(___):
is_authenticated = False # Cut this class attribute
def __init__(self, username, password):
self.username = username
self.password = password

# ========== Cut the code below ==========
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")
# ========== Cut the code above ==========

@property
def password(self):
return self._password

@password.setter
def password(self, new_password):
if isinstance(new_password, str):
if len(new_password) >= 8:
self._password = new_password
else:
print("The password length should be >= 8.")
else:

Fråga AI

expand

Fråga AI

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