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

book
Challenge: Admin

Uppgift

Swipe to start coding

You have a User class from the last challenge.
The methods are corrected (User -> {self.username} in strings).
Let's define the Admin class!

  1. Define the Admin class inherited from the User class.
  2. Define the create_content() admin's method that prints the string:
    f"{self.username} creates the content".
  3. Define the update_content() admin's method that prints the string:
    f"{self.username} updates the content".
  4. Define the delete_content() admin's method that prints the string:
    f"{self.username} deletes the content".

Note

Admin has all the capabilities of User that do not need to be reimplemented. This is an example of how inheritance makes our life easier.

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(f"{self.username} is authenticated")
else:
print("Wrong password!")

def logout(self):
self.is_authenticated = False
print(f"{self.username} is loggouted")


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.login("secret.admin.pswrd")
frank.create_content()
frank.update_content()
frank.delete_content()
frank.logout()

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 2
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(f"{self.username} is authenticated")
else:
print("Wrong password!")

def logout(self):
self.is_authenticated = False
print(f"{self.username} is loggouted")


class ___(___):
def ___(self):
print(f"___")
def ___(self):
print(f"___")
def ___(self):
print(f"___")


frank = Admin("frank.admin", "secret.admin.pswrd")
frank.login("secret.admin.pswrd")
frank.create_content()
frank.update_content()
frank.delete_content()
frank.logout()

Fråga AI

expand
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