Reputation: 14073
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.
Upvotes: 5
Views: 2143
Reputation: 19050
Use a Python @property
Example:
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'))
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.
Upvotes: 10