Зміст курсу
In-Depth Python OOP
In-Depth Python OOP
@property.setter
Let's go back to the User
class with a private attribute password
that cannot be changed in subclasses. How can we access the private password? Let's create a property that returns the private password:
class User: def __init__(self, username, password): self.username = username self.__password = password @property def password(self): return self.__password bob = User("bob123top", "bob123456") print(bob.password)
Currently, we can retrieve the password but cannot change it using the regular syntax. To be able to set a value for a property, we need to use the @{property name}.setter
decorator, where {property name}
is the name of the property we have created (the one for which we want to set a setter).
class User: 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): self.__password = new_password bob = User("bob123top", "bob123456") print("(old)", bob.password) bob.password = "new_bob_password_123" print("(new)", bob.password)
The @password.setter
decorator indicates that this method should be invoked whenever the password
property is assigned a new value. The second password
method is decorated by @password.setter
(where password
is the name of the property method) and set up a new password via assignment (=
) operation. The password
setter method takes two parameters: self
(referring to the instance of the class) and new_password
(representing the new value being assigned to the password
attribute).
Let's choose the following password restrictions:
- The password must be of a type string.
- Password length must be greater than 8.
If the new password does not meet the requirements, the corresponding messages will be printed.
class User: 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 must be >= 8") else: print("Password must be STRING") bob = User("bob123top", "bob123456") print("(old)", bob.password) bob.password = 122 print("(old)", bob.password) bob.password = "123" print("(old)", bob.password) bob.password = "bob.top.user.123" print("(new)", bob.password)
This code ensures that whenever a new value is assigned to the password
attribute, it undergoes validation checks for length and type, providing appropriate feedback if the new password does not meet the requirements.
Дякуємо за ваш відгук!