I have a class definition like
class A(object):
def __init__(self):
self.content = u''
self.checksum = hashlib.md5(self.content.encode('utf-8'))
Now when I change the self.content, I want that self.checksum would automatically calculated. Something from my imagination would be
ob = A()
ob.content = 'Hello world' # self.checksum = '3df39ed933434ddf'
ob.content = 'Stackoverflow' # self.checksum = '1458iabd4883838c'
Is there any magic functions for that? Or is there any event driven approach? Any help would be appreciated.
Use a Python @property
Example:
This way when you "set the value" for
.content
(which happens to be a property) your.checksum
will be part of that "setter" function.This is part of the Python Data Descriptors protocol.