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 =开发者_如何学Python 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 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.
精彩评论