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

book
Challenge: AuthMixin

Task

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.

Solution

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

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 3
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:
print("The password should be string.")


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.password = "some password"
frank.password = "123"
frank.password = 1231241241
frank.login("some password")
frank.logout()
toggle bottom row
some-alt