Зміст курсу
In-Depth Python OOP
In-Depth Python OOP
4. Polymorphism and Abstraction
@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:
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).
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.
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.
Все було зрозуміло?