Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Challenge: Password Validation | Encapsulation
In-Depth Python OOP

book
Challenge: Password Validation

Note

The comments The new code is below and The new code is above will help you to find the new code.

Aufgabe

Swipe to start coding

Let's implement password validation for your code!

  1. Define the password property by the @property decorator.
  2. The password property should return the _password attribute.
  3. Implement the password setter by the @property.setter decorator.
    Take attention: This decorator starts from the property name (@{property_name}.setter).
  4. The password should be string with a length greater than or equal to 8.
  5. Use the self.password property inside the __init__() magic method
    (not a _password).

Lösung

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

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 9
class User:
is_authenticated = False
def __init__(self, username, password):
self.username = username
self.___ = 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")
# ========== The new code is below ==========
___
def password(self):
return ___

@___.setter
def password(self, new_password):
if ___(new_password, ___):
if ___(new_password) >= ___:
self._password = new_password
else:
print("The password length should be >= 8.")
else:
print("The password should be string.")
# ========== The new code is above ==========

class Admin(User):
def create_content(self):

Fragen Sie AI

expand
ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

some-alt