views:

85

answers:

2

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.

A: 

Try self._set_password( password ) in __init__.

S.Lott
I was trying to avoid that if possible as it just feels messy. That is a personal opinion. If there is nothing better, I'll use it.
Chris Smith
+6  A: 

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.

Matt Anderson
Thank you - worked perfectly!
Chris Smith
You must be using Python 2.x. In Python 3 all classes are new-style by default.
AFoglia
That is correct - 2.6.4
Chris Smith