我有一个类似的类定义
class A(object):
def __init__(self):
self.content = u''
self.checksum = hashlib.md5(self.content.encode('utf-8'))
现在,当我更改 self.content 时,我希望 self.checksum 会自动计算。我想象中的东西会是
ob = A()
ob.content = 'Hello world' # self.checksum = '3df39ed933434ddf'
ob.content = 'Stackoverflow' # self.checksum = '1458iabd4883838c'
有什么神奇的功能吗?还是有任何事件驱动的方法?任何帮助将不胜感激。
最佳答案
使用 Python @property
示例:
import hashlib
class A(object):
def __init__(self):
self._content = u''
@property
def content(self):
return self._content
@content.setter
def content(self, value):
self._content = value
self.checksum = hashlib.md5(self._content.encode('utf-8'))
这样,当您为 .content
“设置值”时(恰好是
属性)您的.checksum
将成为该“setter”函数的一部分。
这是 Python Data Descriptors 的一部分协议(protocol)。
关于Python重载变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24933014/