如何从 __init__ 调用属性设置器

发布于 2024-08-13 12:23:06 字数 608 浏览 1 评论 0原文

我有以下 python 代码块:

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)

理论上,这应该打印出密码的 SHA1,但是从构造函数设置 self.password 会忽略定义的属性,而只是将值设置为“password1”。然后 print 语句读取“password1”的值。

我知道这取决于在类与实例上定义的密码,但我不确定如何正确表示它以便它起作用。任何帮助将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本宫微胖 2024-08-20 12:23:06

属性是一个描述符,描述符仅适用于新式类。尝试:

class User(object): ...

而不是:

class User: ...

此处可以找到描述符的良好指南。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文