How do I call a property setter from __init__
Asked Answered
K

1

10

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.

Kramatorsk answered 3/12, 2009 at 15:27 Comment(2)
why do you have instance of _password and password?Unflinching
_password is the storage field. password is the property accessor. _password implies a private field. password is the public protocol.Kramatorsk
M
14

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.

Marker answered 3/12, 2009 at 15:37 Comment(1)
You must be using Python 2.x. In Python 3 all classes are new-style by default.Fulmar

© 2022 - 2024 — McMap. All rights reserved.