如何从 __init__ 调用属性设置器
我有以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
属性是一个描述符,描述符仅适用于新式类。尝试:
而不是:
此处可以找到描述符的良好指南。
A property is a descriptor, and descriptors only work on new-style classes. Try:
instead of:
A good guide to descriptors can be found here.