Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a property setter from __init__

I have the following chunk of python code:

import hashlib

class User:
    def _set_password(self, value):
        self._password = hashlib.sha1(value).hexdigest()

    def _get_password(self):
        return self._password

    password = property(
        fset = _set_password,
        fget = _get_password)

    def __init__(self, user_name, password):
        self.password = password

u = User("bob", "password1")
print(u.password)

This should in theory print out the SHA1 of the password, however setting self.password from the constructor ignores the defined property and just sets the value to "password1". The value of "password1" is then read by the print statement.

I know this is something down to password being defined on the class versus the instance but I'm not sure how to represent it correctly so it works. Any help would be appreciated.

like image 208
Chris Smith Avatar asked Dec 03 '09 15:12

Chris Smith


1 Answers

A property is a descriptor, and descriptors only work on new-style classes. Try:

class User(object): ...

instead of:

class User: ...

A good guide to descriptors can be found here.

like image 156
Matt Anderson Avatar answered Sep 30 '22 14:09

Matt Anderson