Providing Write-Only Attributes
00:00 Providing Write-Only Attributes. You can also create write-only attributes by tweaking how you implement the getter method of your properties. For example, you can make your getter method raise an exception every time you accesses the underlying attribute value.
00:20 On-screen, you’ll see an example of handling passwords with a write-only property.
The initializer of
User takes a username and a password as arguments and stores them in
You use a property to manage how your class processes the input password. The getter method raises an
AttributeError whenever a user tries to retrieve the current password.
.password into a write-only attribute. In the setter method of
.password, you use
os.urandom() to generate a 32-byte random string as your hashing function’s salt. To generate the hashed password, you use
Then you store the resulting hashed password in the non-public attribute
._hashed_password. Doing so ensures that you never save the plaintext password in any retrievable attribute.
01:28 Let’s take a look at the write-only attribute in action.
In this example, you create
john as a
User instance with an initial password. The setter method hashes the password and stores it in
Note that when you try to access
.password directly, you get an
AttributeError. Finally, assigning a new value to
.password triggers the setter method and creates a new hashed password.
In the next section of the course, you’ll see some examples of
property() in action with some practical examples of how to use it.
Become a Member to join the conversation.