【问题标题】:Python overloading variable assignmentPython重载变量赋值
【发布时间】:2014-07-24 11:56:29
【问题描述】:

我有一个类似的类定义

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'

有什么神奇的功能吗?还是有任何事件驱动的方法?任何帮助将不胜感激。

【问题讨论】:

  • 看pythonproperty
  • 你能不接受我的回答吗?

标签: python operator-overloading magic-function


【解决方案1】:

使用 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 Data Descriptors 协议的一部分。

【讨论】:

    猜你喜欢
    • 2013-09-13
    • 2017-12-18
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    相关资源
    最近更新 更多