Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python overloading variable assignment

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.

like image 385
Dewsworld Avatar asked Feb 12 '23 10:02

Dewsworld


1 Answers

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.

like image 114
James Mills Avatar answered Feb 15 '23 02:02

James Mills