Python 重载变量赋值

5 投票
1 回答
2022 浏览
提问于 2025-04-18 14:36

我有一个类的定义,如下所示:

class A(object):
    def __init__(self):
        self.content = u''
        self.checksum = hashlib.md5(self.content.encode('utf-8'))

现在,当我改变 self.content 的时候,我希望 self.checksum 能够自动计算出来。我想象中的情况是:

ob = A()
ob.content = 'Hello world' # self.checksum = '3df39ed933434ddf'
ob.content = 'Stackoverflow' # self.checksum = '1458iabd4883838c'

有没有什么神奇的函数可以做到这一点?或者有没有什么事件驱动的方法?任何帮助都非常感谢。

1 个回答

10

使用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'))

这样,当你为 .content 这个属性“设置值”时,你的 .checksum 就会成为这个“设置值”函数的一部分。

这属于Python的 数据描述符 协议。

撰写回答