Challenge: AuthMixin
Uppgift
Swipe to start coding
Let's make your code more flexible.
- Define the
AuthMixin
class. - Cut the
login
andlogout
methods from theUser
class and insert them into theAuthMixin
body. - Move the
is_authenticated
class attribute to theAuthMixin
. - Inherit the
User
class from theAuthMixin
.
Note
After performing all the actions, you will have an authorization mixin (
AuthMixin
) that can be used for different user classes.
Lösning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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?
Tack för dina kommentarer!
Avsnitt 4. Kapitel 3
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal