Python变量重载赋值

5

我有一个类定义,例如:

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'

有没有魔法函数可以实现这个功能?还是有事件驱动的方法?非常感谢您的帮助。

3
查看Python中的property - behzad.nouri
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将成为该"setter"函数的一部分。
这是Python 数据描述符协议的一部分。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接