Dew*_*rld 3 python operator-overloading magic-function
我有类定义
class A(object):
def __init__(self):
self.content = u''
self.checksum = hashlib.md5(self.content.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
现在,当我更改self.content时,我希望self.checksum会自动计算.我想象中的东西会是
ob = A()
ob.content = 'Hello world' # self.checksum = '3df39ed933434ddf'
ob.content = 'Stackoverflow' # self.checksum = '1458iabd4883838c'
Run Code Online (Sandbox Code Playgroud)
那有什么神奇的功能吗?或者是否有任何事件驱动方法?任何帮助,将不胜感激.
使用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'))
Run Code Online (Sandbox Code Playgroud)
这种方式当你"设置值" .content(恰好是属性)时,你.checksum将成为"setter"函数的一部分.
这是Python 数据描述符协议的一部分.