Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
@property.setter | Encapsulation
In-Depth Python OOP
course content

Зміст курсу

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:

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:

  1. The password must be of a type string.
  2. 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.

How to define a property setter?

Виберіть кілька правильних відповідей

Все було зрозуміло?

Секція 3. Розділ 8
We're sorry to hear that something went wrong. What happened?
some-alt