+-
Python重载变量赋值
我有类定义

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'

那有什么神奇的功能吗?或者是否有任何事件驱动方法?任何帮助,将不胜感激.

最佳答案
使用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“设置值”时(恰好是.content)
属性)你的.checksum将成为“setter”功能的一部分.

这是Python Data Descriptors协议的一部分.

点击查看更多相关文章

转载注明原文:Python重载变量赋值 - 乐贴网