5

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.

1
  • 3
    look into python property Commented Jul 24, 2014 at 11:59

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.