简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM