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

book
Challenge: AbstractAdmin

Tâche

Swipe to start coding

Let's protect your Admin class structure! You need to define the AbstractAdmin class that should have the strict Admin class structure.

  1. Import the ABC class and abstractmethod decorator from the abc package.
  2. Define the AbstractAdmin class inherited from the ABC class.
  3. Define the abstract methods login(), logout(), create_content(), update_content(), and delete_content() via the @abstractmethod decorator.
    Use the pass keyword to miss the function implementation.
  4. Inherit the Admin class from the AbstractAdmin class.
  5. Try to run the code with comments. Look at the Traceback.
  6. Delete comments in the Admin class and run the code again.

Note

Abstract methods should not receive arguments.

Solution

from abc import ABC, abstractmethod


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 AbstractAdmin(ABC):
@abstractmethod
def login():
pass
@abstractmethod
def logout():
pass
@abstractmethod
def create_content():
pass
@abstractmethod
def update_content():
pass
@abstractmethod

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 4. Chapitre 7
from ___ import ___, ___


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

# ========== The new code is below ==========
class ___(___):
@___
def login():
pass
@abstractmethod
___ logout():
pass
@abstractmethod
def create_content():
___
@___
def ___():
pass
___
def delete_content():
pass
# ========== The new code is above ==========


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, ___):
def create_content(self):
print(f"{self.username} creates the content")
def update_content(self):
print(f"{self.username} updates the content")
toggle bottom row
some-alt